<?php

class UserController
{
    private $userModel;
    private $followModel;
    private $autoUidModel;
    private $jpushSetModel;
    private $adminUserModel;
    private $tokenUserModel;
    private $userLoginModel;
    private $userMemberModel;
    private $forbidDeviceModel;
    private $userStatisticsModel;
    private $diaryListCacheModel;
    private $diaryAttachmentModel;
    private $diaryListModel;
    private $userTagModel;
    private $userAccountLogModel;
    private $feedModel;
    private $userSettingModel;
    
    function __construct()/*{{{*/
    {
        $this->userModel            =   new UserModel();
        $this->followModel          =   new FollowModel();
        $this->autoUidModel         =   new AutoUidModel();
        $this->jpushSetModel        =   new JpushSetModel();
        $this->adminUserModel       =   new AdminUserModel();
        $this->tokenUserModel       =   new TokenUserCacheModel();
        $this->userLoginModel       =   new UserLoginModel();
        $this->userMemberModel      =   new UserMemberModel();
        $this->forbidDeviceModel    =   new ForbidDeviceModel();
        $this->userStatisticsModel  =   new UserStatisticsModel();
        $this->diaryListCacheModel  =   new DiaryListCacheModel();
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->diaryListModel       =   new DiaryListModel();
        $this->userTagModel         = 	new UserTagModel();
        $this->userAccountLogModel  =   new UserAccountLogModel();
	    $this->feedModel	        =   new FeedModel();
        $this->userSettingModel     =   new UserSettingModel();
    }/*}}}*/

    public function login($loginInfo)/*{{{*/
    {
        if (empty($loginInfo['account']) || empty($loginInfo['passwd']))
        {
            AC::$errorNo    =   'UC002';
            return  FALSE;
        }
        if (1   !=  AC::API_VERSION) {
            $forbidDeviceStatus =   $this->checkDeviceStatus($loginInfo['deviceSN'], $loginInfo);
            if (empty($forbidDeviceStatus)) return  $forbidDeviceStatus;
        }

        $loginFFIDAllow = $this->diaryListCacheModel->getLoginFFIDAllowList();
        // 手机号登陆
        if (UK::isMobile($loginInfo['account'])) {
            $loginInfo['account'] = UK::getMobileUser($loginInfo['account']);
            $result =   $this->userLoginModel->userLogin($loginInfo);
            if (empty($result)) {
                list($login_type, $area, $loginInfo['account']) = explode('-', $loginInfo['account']);
                $result =   $this->userLoginModel->userLogin($loginInfo);
                if ($result) AC::$errorNo = null;
            }
        }elseif(UK::isFenFenId($loginInfo['account']) && !in_array($loginInfo['account'], $loginFFIDAllow)){
            $result =   $this->userLoginByUid($loginInfo['account'], $loginInfo['passwd']);
        }else{
            $result =   $this->userLoginModel->userLogin($loginInfo);
        }
        
        if (empty($result['uid'])) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        $userInfo['loginInfo']      =   $result;
        $userInfo['userInfo']       =   $this->userModel->getUserInfo($result['uid']);
        $user  = $this->autoUidModel->getUserInfo($result['uid']);
        $userInfo['userInfo']['avatar']      = $user['avatar'];
        $userInfo['userInfo']['max_numbers'] = $user['max_numbers'];
        $userInfo['userInfo']['thirdParty'] = $user['thirdParty'];
        $userInfo['userInfo']['is_vip'] = $user['is_vip'];
		$userInfo['userInfo']['verified'] = $user['verified'];

        $userInfo['userStatistics'] =   $this->userStatisticsModel->getUserStatistics($result);
        $userInfo['userMember']     =   $this->userMemberModel->getMemberInfo($result);
        if (!empty($userInfo['userMember']['uid']))
        {
            $userInfo['userMember']['nextLevelExp'] =   ExpLevel::$levelNeedExp[$userInfo['userMember']['level']];
            unset($result['userMember']['profitDay']);
            unset($result['userMember']['diaryTimes']);
            unset($result['userMember']['commentTimes']);
            unset($result['userMember']['likeTimes']);
            unset($result['userMember']['likedTimes']);
        }
        isset($loginInfo['thirdPartyFirstTime'])    &&  $userInfo['thirdPartyFirstTime']    =   $loginInfo['thirdPartyFirstTime'];
        
        // 过滤第三方登陆账号
        $result = $this->autoUidModel->unsetOpenAccountField($result);
        
        // 更新推送信息
        $this->updatePushInfo($result['uid'], $loginInfo['deviceSN']);
	
        //获取公告状态
        $this->feedModel->UpdateAnnounceCount($result['uid']);
	
        // 记录此次登陆状态
        $this->addLoginOrRegisterLog($result['uid'], 'login', $loginInfo['account'], $user['nickname']);
        
        return  $userInfo;
    }/*}}}*/

    private function userLoginByUid($uid,$passwd){
        if(in_array($passwd,WeakPassword::$weakPwd)){
            AC::$errorNo = 'UCL001';
            return false;
        }


        $autoUidInfo = $this->autoUidModel->getUserBaseInfo(array('uid'=>$uid));
        if(!$autoUidInfo || !$autoUidInfo['account'] || !$autoUidInfo['platform']){
            AC::$errorNo = 'UCL002';
            return false;
        }

        $account ='';
        $password = '';
        if($autoUidInfo['platform'] == 'ffrj') {
            $account = $autoUidInfo['account'];
            $password = $passwd;
        }else{
            $userconnectInfo = $this->userModel->getUserConnnets($uid);
            if($userconnectInfo){
                foreach($userconnectInfo as $info){
                    if($info['open_type'] == AC::$accountTypeConfig['mobile'] || $info['open_type'] == AC::$accountTypeConfig['fenfen']){
                        $account = $info['open_id'];
                        $password = $passwd;
                    }
                }
            }
        }

        if(!$account || !$password){
            AC::$errorNo = 'UCL003';
            return false;
        }

        $userLoginParam = array('account'=>$account,'passwd'=>$password);
        $result = $this->userLoginModel->userLogin($userLoginParam);
        return $result;
    }
    private function updatePushInfo ($uid, $deviceSN) {
        if (empty($uid)) return false;
        
        $pushInfo 	             =  $this->jpushSetModel->getPushInfo(array('uid'=>$uid));
        $extraArr                =  json_decode($pushInfo['jpush_extra'], true);
        $extraArr['appInfoList'] =  AC::$appInfoList;
        $jpush_extra             =  json_encode($extraArr);
        $push = array('uid' => $uid, 'deviceSN' => $deviceSN, 'jpush_extra' => json_encode($extraArr));
        
        if (empty($pushInfo)){
            $this->jpushSetModel->addJpush($push);
        }else{
            $this->jpushSetModel->setPush($push);
        }
        
        return true;
    }
    
    public function emailLogin($loginInfo)
    {
        if (empty($loginInfo['email']) || empty($loginInfo['passwd']))
        {
            AC::$errorNo    =   'UC015';
            return  FALSE;
        }
        $forbidDeviceStatus =   $this->checkDeviceStatus($loginInfo['deviceSN'], $loginInfo);
        if (empty($forbidDeviceStatus)) return  $forbidDeviceStatus;

        $result =   $this->autoUidModel->getUserBaseInfo(array('email' => $loginInfo['email']));
        if (empty($result['account']))
        {
            AC::$errorNo    =   'UC002';
            return  FALSE;
        }
        if ('ffrj'  !=  $result['platform'])
        {
            AC::$errorNo    =   'UC019';
            return  FALSE;
        }
        $loginInfo['account']   =   $result['account'];
        return  $this->login($loginInfo);
    }
    
    public function openUidLogin($loginInfo)
    {
        if (empty($loginInfo['openUid']) || empty($loginInfo['openToken'])  ||  empty($loginInfo['platform']) || !in_array($loginInfo['platform'], AC::$openTypes))
        {
            AC::$errorNo    =   'UC018';
            return  FALSE;
        }
        if (empty($loginInfo['nickname']))
        {
            $loginInfo['nickname']  =   '未设置昵称';
        }
        $forbidDeviceStatus =   $this->checkDeviceStatus($loginInfo['deviceSN'], $loginInfo);
        if (empty($forbidDeviceStatus)) return  $forbidDeviceStatus;

        $openUser   =   UK::getThirdPartyUser($loginInfo['platform'], $loginInfo['openUid']);
        $loginInfo['account']   =   $openUser;
        $loginInfo['passwd']    =   md5($openUser).'@ffrj';
        $loginInfo['thirdPartyFirstTime']   =   2; 
        $result = $this->userLoginModel->getUserInfoByAccount($openUser);
        if (empty($result['account']))
        {
            AC::$errorNo        =   NULL;
            $loginInfo['email'] =   '@ffrj@'. $loginInfo['openUid'];
            $registerResult     =   $this->registerUser($loginInfo);
            $loginInfo['thirdPartyFirstTime']   =   1;
        }

        if (!empty(AC::$errorNo))   return  FALSE;
        return  $this->login($loginInfo);
    }
    
    public function webLogin($loginInfo)
    {
        if (empty($loginInfo['account']) || empty($loginInfo['passwd']))
        {
            AC::$errorNo    =   'UC002';
            return  FALSE;
        }
        $loginInfo['passwd']=   md5($loginInfo['passwd']);
        $result =   $this->userLoginModel->userLogin($loginInfo);
        if (empty($result['uid']))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        $admin  =   $this->getAdminUser($result);
        if (!empty(AC::$errorNo))   return  $admin;

        if (empty($admin['uid']))
        {
            AC::$errorNo    =   'UC012';
            return  'no admin user!';
        }
        if (!empty($admin['status']))
        {
            AC::$errorNo    =   'UC013';
            return  'no authorize!';
        }

        $userInfo['adminInfo']  =   $admin;
        $userInfo['loginInfo']  =   $result;
        $userInfo['userInfo']   =   $this->userModel->getUserInfo($result['uid']);
        DOP::setSession('adminUid', $result['uid']);
        DOP::setSession('nickname', $result['nickname']);
        return  DOP::getSession();
        #   return  $userInfo;
    }

    public function adminModifyUserLoginPasswd($userInfo)
    {
        if (empty($userInfo['passwd']))
        {
            AC::$errorNo    =   'UC021';
            return  FALSE;
        }
        $userBaseInfo   =   $this->autoUidModel->getUserBaseInfo($userInfo);
        if (empty($userBaseInfo['account']))
        {
            AC::$errorNo    =   'UC022';
            return  FALSE;
        }
        
        $result = $this->userLoginModel->updateAccountLoginPasswd($userBaseInfo['uid'], $userBaseInfo['account'], md5($userInfo['passwd']));
        if ($result) {
            $this->addModifyPasswdLog($userBaseInfo['uid'], 'modifypasswd', $userBaseInfo['account']);
        }
        
        return  $result;
    }

    public function getAdminUser($userInfo)
    {
        $result =   $this->adminUserModel->getAdminUser($userInfo);
        if (!empty($result['status']))
        {
            AC::$errorNo    =   'UC013';
            return  ' no authorize!';
        }
        return  $result;
    }

    public function getAdminList($userInfo)
    {
        $result =   $this->adminUserModel->getAdminList($userInfo);
        if (empty($result)  ||  !is_array($result)) return  $result;

        foreach ($result    as  &$admin)
        {
            $userDetail         =   $this->getUserBaseInfo($admin);
            if (empty($userDetail)  ||  empty($userDetail['nickname'])) continue;

            $admin['nickname']  =   $userDetail['nickname'];
            $admin['email']     =   $userDetail['email'];
        }
        return  $result;
    }

    public function chainUser($userInfo)
    {
        if (empty($userInfo['uid']))
        {
            AC::$errorNo    =   'UC011';
            return  FALSE;
        }

        if (empty($userInfo['status'])) $userInfo['status'] =   0;
        else                            $userInfo['status'] =   1;

        $result =   $this->autoUidModel->modifyUserStatus($userInfo);
        if (empty($userInfo['forbidDevice'])) {
            $this->diaryListCacheModel->delUserCache($userInfo['uid']);
            return  $result;
        }

        $result =   $this->autoUidModel->getUserBaseInfo(array('uid' => $userInfo['uid']));

        if($result['deviceSN'] == 'E3F5536A141811DB40EFD6400F1D0A4E' || $result['deviceSN'] == '9BFBE04C81FAD6D79EFC0A5EDB33D7B1')
        {
            return -1;
        }
        if (empty($result['account']))
        {
            AC::$errorNo    =   'UC002';
            return  FALSE;
        }
        $userInfo['account']    =   $result['account'];
        $userInfo['nickname']   =   $result['nickname'];
        $userInfo['deviceSN']   =   $result['deviceSN'];

        $result =   $this->forbidDeviceModel->forbidDevice($userInfo);
        return  $result;
    }

    public function unForbidDevice($userInfo)
    {
        if (empty($userInfo['uid']))
        {
            AC::$errorNo    =   'UC011';
            return  FALSE;
        }
        $uid = intval($userInfo['uid']);
        $result =   $this->forbidDeviceModel->getForbidDeviceInfoByUid($uid);
        if($result && $result['id'] > 0){
            $result =   $this->forbidDeviceModel->unForbidDevice($result['id']);
            return $result;
        }
    
        return  FALSE;
    }
    
    public function removeAdmin($userInfo)
    {
        if (empty($userInfo['uid']))
        {
            AC::$errorNo    =   'UC011';
            return  FALSE;
        }
        $result =   $this->adminUserModel->getAdminUser($userInfo);
        if (empty($result['account']))
        {
            AC::$errorNo    =   'UC014';
            return  ' no find it in admins!';
        }
        $result =   $this->adminUserModel->removeAdminUser($userInfo);
        return  $result;
    }

    public function getUserInfo($userInfo)
    {
        if (empty($userInfo['uid']))
        {
            AC::$errorNo    =   'UC011';
            return  FALSE;
        }

        $result['userInfo']         =   $this->userModel->getUserInfo($userInfo['uid']);
        if (empty($result['userInfo']))
        {
            AC::$errorNo    =   'UC023';
            return  FALSE;
        }
      
        // 用户相册
        $result['userInfo']['photos'] = $this->getUserPhotos($result['userInfo']['photos'], $result['userInfo']['avatar'], AC::HOST_UID);
        
  		// 获取备注名
        $result['userInfo']['nickname']     = $this->autoUidModel->getRemarkName($result['userInfo']);
        $user = $this->autoUidModel->getUserInfo($userInfo['uid'],'',AC::HOST_UID);
        if (!empty($result['userInfo']['photos']) && $result['userInfo']['photos'][0] != $user['avatar']){
            $this->diaryListCacheModel->delUserCache($userInfo['uid']);
            $user['avatar'] = $result['userInfo']['photos'][0];
        }
        $result['userInfo']['sex'] 		= $user['sex'];
        $result['userInfo']['background'] 	= $user['background'];
        $result['userInfo']['tag_list'] 	    = $user['tag_list'];
        $result['userInfo']['avatar']     	= $user['avatar'];
        $result['userInfo']['is_vip'] 	  	= $user['is_vip'];
        $result['userInfo']['is_year_vip'] 	= $user['is_year_vip'];
        $user['is_vip'] && isset($user['vip_info']) && !empty($user['vip_info']) && $result['userInfo']['vip_info'] = $user['vip_info'];
        $result['userInfo']['vip_expire'] = $user['vip_expire'];
        $result['userInfo']['is_ability'] 	= $user['is_ability'];
        $result['userInfo']['ability_level']	= $user['ability_level'];
        $result['userInfo']['verified']	    = $user['verified'];
        $result['userInfo']['max_numbers'] 	= intval($user['max_numbers']);
	    // 兼容老版本，过几个版本可以去掉is_follow
        $result['userInfo']['is_follow']    = $this->autoUidModel->checkUserFollow(AC::HOST_UID, $userInfo['uid']);
        $result['userInfo']['is_mefollow']  = $user['is_mefollow'];
        $result['userInfo']['thirdParty']   = $user['thirdParty'];
        $result['userInfo']['subscribe_level']   = $user['subscribe_level'];
        $result['userInfo']['subAuthorType'] = '';
        if($result['userInfo']['subscribe_level']){
            $no = intval($result['userInfo']['subscribe_level']/100);
            $nameNo = intval($result['userInfo']['subscribe_level']%100);
            $name = '';
            if(array_key_exists($nameNo, AC::$subAuthorType)){
                $name = AC::$subAuthorType[$nameNo];
            }
            $result['userInfo']['subAuthorType'] = '第'.$no.'批签约的'.$name.'作者';
        }
        unset($result['userInfo']['tags']);
        $result['userMember']        =   $this->userMemberModel->getMemberInfo($userInfo);
        if (!empty($result['userMember']['uid']))
        {
            $result['userMember']['nextLevelExp']   =   ExpLevel::$levelNeedExp[$result['userMember']['level']];
        }
        
        // 判断是否初始化
        $result['userStatistics']   =   $this->userStatisticsModel->getUserStatistics($userInfo);
        if (AC::HOST_UID    !== $userInfo['uid'])
        {
            $result['followInfo']   =   $this->followModel->getFollowInfo(array('uid' => AC::HOST_UID, 'fUid' => $userInfo['uid']));
            unset($result['userMember']['traffic']);
            unset($result['userMember']['allTraffic']);
            unset($result['userMember']['profitDay']);
            unset($result['userMember']['diaryTimes']);
            unset($result['userMember']['commentTimes']);
            unset($result['userMember']['likeTimes']);
            unset($result['userMember']['likedTimes']);
            unset($result['userInfo']['account']);
            unset($result['userInfo']['email']);
            unset($result['userInfo']['thirdParty']);
        }
        
        // 邮箱输出过滤
        if (preg_match("/^(@ffrj).*/", $result['userInfo']['email'])){
            $result['userInfo']['email'] = "";
        }
        
        // 将qq登录以及微博登录的帐号不返回给客户端
        $result['userInfo'] = $this->autoUidModel->unsetOpenAccountField($result['userInfo']);
        $result = $this->autoUidModel->unsetOpenAccountField($result);
        return  $result;
    }
    
    /**
     * 获取用户相册
     * @param unknown $photos_json
     * @param unknown $user_avatar
     * @param unknown $host_uid
     * @return Ambigous <multitype:, string>
     */
    private function getUserPhotos ($photos_json, $user_avatar, $host_uid) {
        $result = $photos = $avatar = array();
        if($photos_json){
            $photos = json_decode($photos_json,true);
        }
        
        if(empty($photos)){
            $result = $avatar;
            if ($user_avatar){
                $avatar[] = UK::getuseravatarurl($host_uid , $user_avatar);
                $result = $avatar;
            }
        }else{
            foreach($photos as $pic){
                $result[] =  UK::getuseravatarurl($host_uid ,$pic);
            }
        }
        
        return $result;
    }

    public function getUserToken($userInfo)/*{{{*/
    {
        $result =   $this->tokenUserModel->getUserToken($userInfo);
        return  $result;
    }/*}}}*/

    public function makeUserToken($userInfo)/*{{{*/
    {
        $result =   $this->tokenUserModel->makeUserToken($userInfo);
        return  $result;
    }/*}}}*/

    public function getUserBaseInfo($userInfo)/*{{{*/
    {
        $result =   $this->autoUidModel->getUserBaseInfo($userInfo);
        if (empty($result['uid'])   ||  empty($result['account']))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        return  $result;
    }/*}}}*/
    
    /**
     * 从redis缓存中获取用户信息,主要用于内部调用
     * @param unknown $uid
     * @return boolean|Ambigous <Ambigous, boolean, string>
     */
    public function getUserCacheInfo($uid){
        $result    =    $this->autoUidModel->getUserInfo($uid);
        if (empty($result['uid']))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        return  $result;
    }
    
    public function getUserBaseInfoUseLike($userInfo)/*{{{*/
    {
        $result =   $this->autoUidModel->getUserBaseInfoUseLike($userInfo);
        if (empty($result)) {
            AC::$errorNo = null;
            return array();
        }
        
        foreach( $result as &$value ){
           $value['nickname']  =    $this->autoUidModel->getRemarkName($value);
           $value['user']['nickname']  =    $this->autoUidModel->getRemarkName($value['user']);
        }
        
        return  $result;
    }/*}}}*/
    
    public function getUserList($userInfo)/*{{{*/
    {
        $result =   $this->autoUidModel->getUserList($userInfo);
        return  $result;
    }/*}}}*/

    public function registerUser($userInfo)/*{{{*/
    {
        if (empty($userInfo['account']) ||  empty($userInfo['passwd']))
        {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }

        // 注册账号类型筛选及过滤
        $register_type = UK::getAccountTpye($userInfo['account']);
        if (UK::isMobile($userInfo['account'])) $register_type = AC::ACCOUNT_TYPE_MOBILE;
        $access = $this->shieldAccountOfCommon($register_type);
        if (!$access) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return FALSE;
        }

        $forbidDeviceStatus =   $this->checkDeviceStatus($userInfo['deviceSN']);
        if (empty($forbidDeviceStatus)) return  $forbidDeviceStatus;
        if('' ==  $userInfo['nickname']){
            $userInfo['nickname'] = "粉粉用户";
        }
        if('' ==  $userInfo['email']){
            $userInfo['email'] = '@ffrj@'. $userInfo['account'];
        }
        
        $userInfo['nickname']   =   $this->checkNickname($userInfo['nickname']);
        
        // 手机注册
        if ($register_type == AC::ACCOUNT_TYPE_MOBILE && $userInfo['code']) {
            $mobileCodeIsValid = $this->autoUidModel->checkMobileCodeIsValid($userInfo['account'], $userInfo['code'], UK::getMobileCodeType('mobile_register'));
            if (AC::$errorNo) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return  FALSE;
            }
            
    	    $userInfo['account'] = UK::getMobileUser($userInfo['account']);
    	    $userInfo['email']   = '@ffrj@'. $userInfo['account'];
        }
        
        $uid    =   $this->autoUidModel->initAutoUid($userInfo);
        if ($userInfo['nickname'] === "粉粉用户"){
            $userInfo['nickname'] .= $uid;
        }

        if (empty($uid)) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        $userInfo['uid']    =   $uid;
        $userInfo['type']   =   $register_type;
        $initUserLogin      =   $this->userLoginModel->initUserLogin($userInfo);
        if (empty($initUserLogin))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        $initUserStatistics =   $this->userStatisticsModel->initUserStatistics(array('uid' => $uid));
        if (empty($initUserStatistics))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        $initUserMember     =   $this->userMemberModel->initUserMember($userInfo);
        if (empty($initUserMember))
        {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        $registerUser       =   $this->userModel->registerUser($userInfo);
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        // 关注官方账号
        $this->followOfficialAccounts($uid, $userInfo['nickname']);
        
        // 更新推送设置
        $this->jpushSetModel->addJpush(array('uid' => $uid,'deviceSN' => AC::$appInfoList[5]));
        
        // 记录此次注册
        $this->addLoginOrRegisterLog($uid, 'register', $userInfo['account'], $userInfo['nickname']);

        // 返回gotype的密码
        $thirdParty = array('gotype_token' => $this->autoUidModel->getGoTypePwd($uid));
        RedisPool::addUserEventCreateJob('regUser', UK::JsonFormat([ 'e'=>'regUser', 'c'=>['uid'=>intval($uid)] ]));
        
        return  array('uid' =>  strval($uid), 'thirdParty' => $thirdParty);
    }/*}}}*/

    private function shieldAccountOfCommon ($register_type) {
        $account_type_allowed = array(
            AC:: ACCOUNT_TYPE_QQ,
            AC:: ACCOUNT_TYPE_WEIBO,
            AC:: ACCOUNT_TYPE_WECHAT,
            AC::ACCOUNT_TYPE_MOBILE
        );
        if (!in_array($register_type, $account_type_allowed)){
            AC::$errorNo  = 'URGT001';
            AC::$errorMsg = '账号注册不可用，请使用第三方登录或升级到新版本进行注册~';
            return false;
        }

        return true;
    }

    /**
     * 关注官方账号
     * @param unknown $uid
     * @return boolean
     */
    private function followOfficialAccounts ($uid, $nickname) {
        if (empty($uid) || strlen($nickname) < 1) return false;
        
        $num = 0;
        $uids = AC::$officialAccounts['register'];
        foreach ($uids as $fUid){
            $this->followAccount($uid, $fUid, $nickname);
            if (AC::$errorNo){
                return FALSE;
                break;
            }
            
            AC::$userStatistics[$fUid]['newLikeMeTimes']  =   0;
            $num++;
        }
        
        AC::$errorNo = null;
        $num = $num > count($uids) ? count($uids) : $num;
        AC::$userStatistics[$uid]['meFollowTimes']    =   $num;
        RedisPool::addGearmanJob("timeline", array("uid" => $uid), $uid);
        return TRUE;
    }
    
    /**
     * 关注用户
     * @param unknown $uid
     * @param unknown $fUid
     * @return boolean
     */
    private function followAccount ($uid, $fUid, $nickname) {
        $fUidBaseInfo       =   $this->autoUidModel->getUserInfo($fUid);
        if (!isset($fUidBaseInfo['nickname'])) {
            AC::$errorNo    =   'FOC003';
            return  FALSE;
        }
        
        $result =   $this->followModel->meFollow(array('uid' => $uid, 'fUid' => $fUid));
        if (empty($result)) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        // redis增加好友列表 并重新获取用户关注列表
        $this->diaryListCacheModel->addFriends($uid, $fUid);
        $this->diaryListCacheModel->addFans($fUid, $uid);
        
        // 重建好友粉丝列表
        $this->autoUidModel->rebuildUserFollowersAndFansList($uid);
        $this->autoUidModel->rebuildUserFollowersAndFansList($fUid);
        
        // 计数及动态更新
        AC::$userStatistics[$uid]['meFollowTimes']    =   1;
        AC::$userStatistics[$fUid]['followMeTimes']   =   1;
        AC::$userStatistics[$fUid]['newFollowTimes']  =   0;
        AC::$userStatistics[$fUid]['newLikeMeTimes']  =   1;
        AC::$feedInfo   =   array(
            'uid'               =>  $uid,
            'eUid'              =>  $uid,
            'eNickname'         =>  $nickname,
            'authorUid'         =>  $fUid,
            'authorNickname'    =>  $fUidBaseInfo['nickname'],
            'type'              =>  AC::FEED_FOLLOW,
            'content'           =>  'follow la~ follow la~!',
        );
        
        // 推送
        $followInfo = array('uid' => $uid, 'fUid' => $fUid, 'nickname' => $nickname, 'fNickname' => $fUidBaseInfo['nickname']);
        $push	=	new PushController();
        $push->push($followInfo, "pushFollow");
        
        return $result;
    }

    public function removeUser($userInfo)/*{{{*/
    {
        $result = FALSE;
        return  $result;
    }/*}}}*/

    public function updateLoginPasswd($userInfo)/*{{{*/
    {
        if (AC::HOST_UID != $userInfo['uid']) {
            AC::$errorNo    =   'UC003';
            return  FALSE;
        }
        
        $info   =   $this->userModel->getUserInfo($userInfo['uid']);
        if (empty($info['account'])) {
            AC::$errorNo    =   'UC004';
            return  FALSE;
        }
        
        // 更新账号密码
        $userConnects = $this->getConnent();
        if ($userConnects['connents']) {
            $connents = $this->assembleConnectsData($userConnects['connents']);
            if ($connents['fenfen']) {
                $fenfenAccount = $connents['fenfen'];
                $result = $this->updateUserLoginPasswd($fenfenAccount['uid'], $fenfenAccount['account'], $userInfo['newPasswd'], "updateLoginPasswd", $userInfo['oldPasswd']);
                if (empty($result)) return $result;
            }
            
            if ($connents['mobile']) {
                $mobileAccount = $connents['mobile'];
                $account = UK::getMobileUser($mobileAccount['account']);
                $result = $this->updateUserLoginPasswd($mobileAccount['uid'], $account, $userInfo['newPasswd'], "modifyMobileLoginPasswd");
                if (empty($result)) return $result;
            }
        }
        
        if ($result) {
            $this->addModifyPasswdLog(AC::HOST_UID, 'modifypasswd', $info['account']);
        }
        
        return  $result;
    }/*}}}*/

    public function updateUserPassword($uid, $newpasswd, $oldpasswd)
    {
        if (empty($uid) || empty($newpasswd) || empty($oldpasswd) || strlen($oldpasswd) < 32) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }

        $info   =   $this->userModel->getUserInfo($uid);
        if (empty($info['account'])) {
            AC::$errorNo    =   'UC004';
            return  FALSE;
        }

        $valid  = $this->checkPasswdIsValid($uid, $oldpasswd);
        if (empty($valid))
        {
            AC::$errorNo    =   'UC009';
            return  FALSE;
        }

        // 更新账号密码
        $userConnects = $this->getConnent(array('uid' => $uid));
        if ($userConnects['connents']) {
            $connents = $this->assembleConnectsData($userConnects['connents']);
            if ($connents['fenfen']) {
                $fenfenAccount = $connents['fenfen'];
                $result = $this->updateUserLoginPasswd($fenfenAccount['uid'], $fenfenAccount['account'], $newpasswd, "updateLoginPasswd", $oldpasswd);
                if (empty($result)) return false;
            }

            if ($connents['mobile']) {
                $mobileAccount = $connents['mobile'];
                $account = UK::getMobileUser($mobileAccount['account']);
                $result = $this->updateUserLoginPasswd($mobileAccount['uid'], $account, $newpasswd, "modifyMobileLoginPasswd");
                if (empty($result)) return false;
            }
        }

        return true;
    }

    /**
     * 验证原密码是否正确
     * @param $uid
     * @param $oldPasswd
     * @return bool
     */
    public function checkPasswdIsValid($uid, $oldPasswd)
    {
        if (empty($uid) || empty($oldPasswd)) {
            AC::$errorNo    =   'UC001';
            return  false;
        }

        $autoUidInfo = $this->autoUidModel->getUserBaseInfo(array('uid'=>$uid));
        if(!$autoUidInfo || !$autoUidInfo['account'] || !$autoUidInfo['platform']){
            AC::$errorNo = 'UC004';
            return false;
        }

        $account ='';
        if($autoUidInfo['platform'] == 'ffrj') {
            $account = $autoUidInfo['account'];
        }else{
            $userconnectInfo = $this->userModel->getUserConnnets($uid);
            if($userconnectInfo){
                foreach($userconnectInfo as $info){
                    if($info['open_type'] == AC::$accountTypeConfig['mobile'] || $info['open_type'] == AC::$accountTypeConfig['fenfen']){
                        $account = $info['open_id'];
                    }
                }
            }
        }

        if(empty($account)){
            AC::$errorNo = 'UC004';
            return false;
        }

        $loginAccount = $this->userLoginModel->getUserInfo(array('account' => $account, 'passwd' => $oldPasswd));
        if (empty($loginAccount))
        {
            AC::$errorNo    =   'UC009';
            return  false;
        }

        return true;
    }
    
    private function assembleConnectsData ($list) {
        $binds = array();
        foreach ($list as $val) {
            $binds[$val['type']] = $val;
        }
    
        return $binds;
    }
    
    private function updateUserLoginPasswd ($uid, $account, $newPasswd, $type="updateLoginPasswd", $oldPasswd = '', $mobilecode = '') {
        if (empty($uid) ||  empty($account) ||  empty($newPasswd)) {
            AC::$errorNo    =   'ULM007';
            return  FALSE;
        }
        
        if ($type == "updateLoginPasswd") {
            if (empty($oldPasswd)) {
                AC::$errorNo = 'ULM007';
                return false;
            }
            
            if ($oldPasswd  ==  $newPasswd) {
                AC::$errorNo    =   'ULM014';
                return  FALSE;
            }
        }
        
        $result = $this->userLoginModel->updateAccountLoginPasswd($uid, $account, $newPasswd, $oldPasswd);
        return $result;
    }
    
    /**
     * 邮箱找回密码
     * @param unknown $userInfo
     * @return boolean
     */
    public function resetPasswd($userInfo) {
        if (empty($userInfo['email']))
        {
            AC::$errorNo    =   'UC007';
            return  FALSE;
        }
        
        $isEmail = UK::isEmail($userInfo['email']);
        if (!$isEmail){
            AC::$errorNo    =   'UC007';
            return FALSE;
        }
        
        $checkEmail     =   $this->checkPrivateEmail($userInfo['email']);
        if (empty($checkEmail)) return  FALSE;

        $userBaseInfo   =   $this->autoUidModel->getUserBaseInfo(array('email' => $userInfo['email']));
        if (empty($userBaseInfo['account']))
        {
            AC::$errorNo    =   'UC008';
            return  FALSE;
        }
        
        $newPasswd =   UK::makeRandPasswd();
        
        // 发邮件
        $res_email = $this->userLoginModel->sendEmail($userInfo['email'], $userBaseInfo['account'], $newPasswd);
        if (!$res_email) return false;
        
        // 更新账号密码
        $result = $this->updateUserPasswd($userBaseInfo['uid'], md5($newPasswd));
        if ($result) {
            $this->addModifyPasswdLog($userBaseInfo['uid'], 'modifypasswd', $userBaseInfo['account']);
        }
        
        return  $result;

    }/*}}}*/
    
    /**
     * 修改手机号登陆密码
     * @param unknown $info
     * @return boolean|Ambigous <boolean, unknown, number, resource>
     */
    public function modifyMobileLoginPasswd($info) {
        $mobile = $info['mobile'];
        $passwd = $info['passwd'];
        $code   = $info['code'];
        if (empty($mobile) || empty($passwd) || empty($code) || strlen($passwd) != 32) {
            AC::$errorNo    =   'UC021';
            return  FALSE;
        }
        
        // 验证手机号
        $isMobile = UK::isMobile($mobile);
        if (!$isMobile) {
            AC::$errorNo    =   'UC020';
            return  FALSE;
        }
        
        $account        =   UK::getMobileUser($mobile);
        // 验证码是否合理
        $mobileCodeIsValid = $this->autoUidModel->checkMobileCodeIsValid($mobile, $code, UK::getMobileCodeType('mobile_resetpasswd'));
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        // 用户账号是否存在
        $mobileInfo = $this->userLoginModel->getUserInfoByAccount($account);
        if (empty($mobileInfo)) {
            AC::$errorNo  = 'UC008';
            return FALSE;
        }
        // 更新账号密码
        $result = $this->updateUserPasswd($mobileInfo['uid'], $passwd);
        if ($result) {
            $this->addModifyPasswdLog($mobileInfo['uid'], 'modifypasswd', AC::$hostUserBaseInfo['account']);
        }
        
        return $result;
    }

    /**
     * 修改邮箱登陆密码
     * @param unknown $info
     * @return boolean|Ambigous <boolean, unknown, number, resource>
     */
    public function modifyEmailLoginPasswd($info) {
        $email = $info['email'];
        $passwd = $info['passwd'];
        $code   = $info['code'];
        if (empty($email) || empty($passwd) || empty($code) || strlen($passwd) != 32) {
            AC::$errorNo    =   'UC021';
            return  FALSE;
        }

        // 验证传参
        $isEmail = UK::isEmail($email);
        $codeType   = UK::getMobileCodeType('mobile_resetpasswd');
        if (!$isEmail || !$codeType) {
            AC::$errorNo  =   'GC034';
            return  FALSE;
        }

        $emailCodeIsValid = $this->autoUidModel->checkEmailCodeIsValid($email, $code, $codeType);
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        // 修改密码需要查询账号是否存在
        $userBaseInfo   =   $this->autoUidModel->getUserBaseInfo(array('email' => $email));
        if (empty($userBaseInfo)) {
            AC::$errorNo  =   'UC039';
            return  FALSE;
        }

        // 更新账号密码
        $result = $this->updateUserPasswd($userBaseInfo['uid'], $passwd);
        if ($result) {
            $this->addModifyPasswdLog($userBaseInfo['uid'], 'modifypasswd', $email);
        }

        return $result;
    }
    
    private function updateUserPasswd ($uid, $passwd, $type="resetPasswd") {
        if (empty($uid) || empty($passwd) || strlen($passwd) != 32) return false;
        
        $userConnects = $this->getConnent(array('uid' => $uid));
        if ($userConnects['connents']) {
            $connents = $this->assembleConnectsData($userConnects['connents']);
            if ($connents['fenfen']) {
                $fenfenAccount = $connents['fenfen'];
                $result = $this->updateUserLoginPasswd($fenfenAccount['uid'], $fenfenAccount['account'], $passwd, $type);
                if (empty($result)) return $result;
            }
        
            if ($connents['mobile']) {
                $mobileAccount = $connents['mobile'];
                $account = UK::getMobileUser($mobileAccount['account']);
                $result = $this->updateUserLoginPasswd($mobileAccount['uid'], $account, $passwd, $type);
                if (empty($result)) return $result;
            }
        }
        
        return true;
    }
    
    public function editUserInfo($userInfo)/*{{{*/
    {
        $this->editUserBaseInfo($userInfo);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }
        return  TRUE;
    }/*}}}*/
    
    public function modifyUserInfo($userInfo)/*{{{*/
    {
        $this->editUserBaseInfo($userInfo);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }
        if (isset($userInfo['background'])) {
            $user    =    $this->autoUidModel->getUserInfo($userInfo['uid']);
            return  $user['background'];
        }
        
        if (isset($userInfo['image'])) {
            $user    =    $this->autoUidModel->getUserInfo($userInfo['uid']);
            return $user['avatar'];
        }
        
        return  TRUE;
    }/*}}}*/
    
    /**
     * 好友分组以及备注入口
     * @param unknown $info
     * @return boolean|unknown
     */
    public function user($info){
        if (empty($info['action'])){
            AC::$errorNo    =    'UC033';
            return FALSE;
        }
        // 方法列表
        $ac_list    =    array('getHighQualitySubscription','getSubscriptionList','rebindPhone','getDuiBaAutoLoginUrl','setRmark','signout','getUploadSecret','accountBind', 'getConnent','accountUnbind','photos', 'getAllTags', 'searchUserByTag', 'modifyUserTag','getFemaleAuth','applyForFemaleAuth','importDataToRedis');
        if (!in_array($info['action'], $ac_list)){
            AC::$errorNo    =    'UC034';
            return FALSE;
        }
        
        $result = $this->$info['action']($info);
        
        return $result;
    }

    public function rebindPhone($info){
        $uid = HOST_UID;
        $passwd = $info['passwd'];
        $phone = $info['phone'];
        $code = $info['code'];
        if(intval($uid) < 1  || empty($passwd) || !UK::isMobile($phone) || empty($code)){
            AC::$errorNo = 'URP001';
           return false;
        }
        try {
            $this->autoUidModel->begin();
            
            $baseInfo = $this->autoUidModel->getUserBaseInfo(array('uid'=>$uid));
            if(!$baseInfo){
                AC::$errorNo = 'URP002';
                return false;
            }
            
            $checkCode = $this->autoUidModel->checkMobileCodeIsValid($phone, $code, UK::getMobileCodeType('mobile_update'));
            if (AC::$errorNo) {
                UK::varDump(AC::$errorNo, __METHOD__);
                return FALSE;
            }
             
            $phoneStatus = $this->userLoginModel->getUserInfoByAccount('mobile-'.$phone);
            if($phoneStatus){
                AC::$errorNo = 'URP0012';
                AC::$errorMsg = '该账号已被绑定';
                return false;
            }
            
            $connets = $this->getConnent();
            if(AC::$errorNo){
                UK::varDump(AC::$errorNo, __METHOD__);
                return false;
            }
           
            $oldPhone = '';
            $accountType = 0;
            foreach ($connets['connents'] as $value){
               if($value['type']=='mobile'){
                  $oldPhone = $value['account'];
                  $accountType = $value['accountType'];
                   break;
               }
            }
          
            if(empty($oldPhone)){
                AC::$errorNo = 'URP009';
                return false;
            }
            $oldPhone = 'mobile-'.$oldPhone;
            $userLoginInfo = array('account' => $oldPhone, 'passwd' => $passwd);
        
            $userLogin = $this->userLoginModel->getUserInfo($userLoginInfo);
        
            if (!$userLogin) {
                AC::$errorNo = 'URP003';
                return false;
            }
            //手机号注册
            if ($accountType == '1') {
                $result = $this->replacePhoneNumberOfRegistration($userLogin, $phone, $passwd,$baseInfo);
                if (!$result) {
                    return false;
                }
            }elseif($accountType == '2'){
                //其他方式注册,绑定手机号

                $result = $this->replacePhoneNumberOfBinding($oldPhone, $phone, $passwd, $uid);
                if (!$result) {
                    return false;
                }
            }else{
                AC::$errorNo = 'URP002';
                return false;
            }
            $this->autoUidModel->commit();
        }catch (DBException $e) {
            $this->autoUidModel->rollback();
        }

        $this->diaryListCacheModel->delUserCache($info['uid']);
        return true;
    }

    private function replacePhoneNumberOfBinding($account, $phone, $passwd, $uid){
        $newAccount = 'mobile-'.$phone;
        $where = array(
            'open_id' => $account,
                'uid'     => $uid
        );
        $value = array(
            'open_id' => $newAccount,
        );
       $userConnnet = $this->userModel->updateUserConnnet($where, $value, $uid);
       if(!$userConnnet){
            AC::$errorNo = 'URP010';
            return false;
       }

       $userLoginInfo = array('account'=>$account,'passwd'=>$passwd);
       $userLogin = $this->userLoginModel->getUserInfo($userLoginInfo);
       if(!$userLogin){
            AC::$errorNo = 'URP011';
            return false;
       }

       $updateUserLogin = $this->updateUserLoginInfo($userLogin,$newAccount,$passwd);
       if(!$updateUserLogin){
            return false;
       }
        return true;
    }

    private function replacePhoneNumberOfRegistration($userLogin, $phone, $passwd,$baseInfo){
       // 更改autoUid account 手机号
        if(!$userLogin['uid'] || !$userLogin['account']){
            AC::$errorNo = 'URP001';
            return false;
        }

        $account = 'mobile-'.$phone;
        //@ffrj@mobile-86-17737037985
        if(UK::isMobile(substr($baseInfo['email'],13))){
            $email = '@ffrj@mobile-'.$phone;
        }
        $value = array('account'=>$account);
        $where = array('uid'=>$userLogin['uid'], 'account'=>$userLogin['account']);
        if($email){
            $value['email'] = $email;
        }
        $updateAutoUid = $this->autoUidModel->updateUserBaseInfo($where, $value);
        if(!$updateAutoUid){
            AC::$errorNo = 'URP004';
            return false;
        }

        //	更改userInfo account 手机号
        $updateUserInfo = $this->userModel->updateUserInfo($where, $value, $userLogin['uid']);
        if(!$updateUserInfo){
            AC::$errorNo = 'URP005';
            return false;
        }

        $updateUserLogin = $this->updateUserLoginInfo($userLogin,$account,$passwd);
        if(!$updateUserLogin){
            return false;
        }
        return true;
    }

    private function updateUserLoginInfo($userLogin,$account,$passwd){
        //	写入userLogin account 新手机号
        $login = array(
            'uid'       =>  $userLogin['uid'],
            'account'   =>  $account,
            'passwd'    =>  $passwd,
            'nickname'  =>  $userLogin['nickname'],
            'loginTime' =>  AC::SERVER_TIME,
            'loginIp'   =>  UK::getClientIp(),
            'status'    =>  AC::REGISTER_DEFAULT_STATUS,
        );
        isset($userLogin['image'])       &&  $login['image']      =   $userLogin['image'];
        isset($userLogin['type'])        &&  $login['type']       =  intval($userLogin['type']);
        $userLoginInit = $this->userLoginModel->initUserLogin($login);
        if(!$userLoginInit){
            AC::$errorNo = 'URP006';
            return false;
        }

        //删除老的登录信息
        $oldUserLoginInfo = $this->userLoginModel->delUserInfoByAccount($userLogin['account'], $userLogin['uid']);
        if(!$oldUserLoginInfo) {
            AC::$errorNo = 'URP007';
            return false;
        }
        return true;
    }

    /**
     * getFemaleAuth女生认证判断
     * @param array(uid)
     * @return array(uid、status、type、auth_url、auth_message，dateline,user)
     */
     public function getFemaleAuth($info){
        $uid      = $info['uid'];
        $host_uid = AC::HOST_UID;
        if (intval($uid) < 1 || $uid != $host_uid){
        	AC::$errorNo="CMFA001";
            return false;
        }
        
        $userInfo = $this->autoUidModel->getUserInfo($uid);
        if (empty($userInfo)) {
            return false;
        }
        
        //获取女生认证信息
        $femaleAuthInfo = $this->autoUidModel->getFemaleAuthInfo($uid);
        $femaleAuthInfo = $this->assembleStatusOfApply($femaleAuthInfo);
        $femaleAuthInfo['user'] = $userInfo;
        
        //对数据进行组装
        $result = $this->restructFemaleAuthData($host_uid, $femaleAuthInfo);
    
        return $result;
    }
    
    private function assembleStatusOfApply ($femaleAuthInfo) {
        if (empty($femaleAuthInfo)) {
            return array('canapply' => AC::$femalApplyStatus['yes']);
        }
        
        $femaleAuthInfo['canapply'] = AC::$femalApplyStatus['no'];
        if($femaleAuthInfo['status'] == AC::$femaleAuthStatus['again_apply']) {
            $femaleAuthInfo['canapply'] = AC::$femalApplyStatus['yes'];
        }
        
        return $femaleAuthInfo;
    }
    
    //对数据进行组装
    private function restructFemaleAuthData ($host_uid, $info) {
        $result = array(
            'uid'           =>  strval($host_uid),
            'status'        =>  AC::$femaleAuthStatus['default'],
            'type'          =>  0,
            'auth_url'      =>  '',
            'canapply'      =>  '1',
            'user'          => (object) array()
        );

        isset($info['status'])   && $result['status']   = strval($info['status']);
        isset($info['type'])     && $result['type']     = strval($info['type']);
        isset($info['auth_url']) && $result['auth_url'] = strval(AC::getProtocolUriByOS(AC::$hostOfFenFen['media']).$info['auth_url']);
        isset($info['canapply']) && $result['canapply'] = strval($info['canapply']);
        isset($info['user'])     && $result['user']     = $info['user'];
      
        return $result;
    }
    
    /**
     * 申请女生认证
     * @param array(uid,auth_url,type,msg_id) 
     * @return array | boolean
     */
    public function applyForFemaleAuth($info){
        $uid         =    $info['uid'];
        $auth_url    =    $info['auth_url'];
        $type        =    $info['type'];
        
        // 1. 参数验证
        if(intval($uid) < 1 || empty($auth_url) || !in_array($type, AC::$femalAuthUploadType)){
        	AC::$errorNo = 'CMFA001';
            return false;
        }
        
        $userInfo =  $this->autoUidModel->getUserInfo($uid);
        if (empty($userInfo)) return false;
        
        $info['nickname'] = $userInfo['nickname'];
        if($userInfo['sex'] != AC::$sex['girl']){
        	AC::$errorNo = 'CMFA004';
        	return false;
        }
        
        //更新或增加记录需要的数据
        $femaleAuthData =$this->assembleMysqlDataOfFemale($info);

        $femaleAuthInfo = $this->autoUidModel->getFemaleAuthInfo($uid);
    
        if(empty($femaleAuthInfo)){
            //添加认证信息
            return $this->addFemaleAuth($uid,$femaleAuthData);
        }

        if($femaleAuthInfo['status'] != AC::$femaleAuthStatus['again_apply']){
        	AC::$errorNo = 'CMFA004';
        	return false;
        }
        
        //更新认证信息
        return $this->updateFemaleAuth($uid,$femaleAuthData);
    }
    
    //添加认证信息
    private function addFemaleAuth($uid,$femaleAuthData){
        
        if(intval($uid) < 1 || empty($femaleAuthData) || empty($femaleAuthData['auth_url'])) return FALSE;
        
        $femaleAuthData['uid'] =$uid;
        $femaleAuthData['time'] = AC::SERVER_TIME;
        //增加认证信息
        $retVal=$this->autoUidModel->addFemaleAuth($femaleAuthData);
         
        $result=$this->getFemaleAuth(array('uid'=>$uid));
         
        return  $result;
    }
    
    //更新认证信息
    private  function  updateFemaleAuth($uid,$femaleAuthData){
        
        if(intval($uid) < 1||empty($femaleAuthData) || empty($femaleAuthData['auth_url'])) return FALSE;
        //更新认证信息
        $retVal=$this->autoUidModel->updateFemaleAuth($uid,$femaleAuthData);
    
        $result=$this->getFemaleAuth(array('uid'=>$uid));
         
        return  $result;
    }
    
    //组装增加或更新的数据
    private function assembleMysqlDataOfFemale($info){
        $uid         =    $info['uid'];
        $auth_url    =    $info['auth_url'];
        $type        =    $info['type'];
     
        $nickname    =    $info['nickname'];
     
        
        $dateline    =   AC::SERVER_TIME + 259200; // 加3天时间    
        $content     = $nickname.'申请女生认证';
        $result =array(
            'content'   =>  $content,
            'auth_url'  =>  $auth_url,
            'type'      =>  $type,
            'status'    =>  AC::$femaleAuthStatus['apply'],
            'applytime' =>  AC::SERVER_TIME,
            'dateline'  =>  $dateline,
        );
	
        return $result; 
    }
    
    /**
     * 编辑用户标签
     * @param unknown $userTag
     * @return boolean
     */
    private function modifyUserTag($info){
        $uid    = AC::HOST_UID;
        $tagStr = UK::getstr($info['tags'], 500, '', 1);
        
        $result = $this->userTagModel->editUserTags($uid, $tagStr);
        if ($result) {
            // 删除用户缓存
            $this->diaryListCacheModel->delUserCache($uid);
        }
         
        return $result;
    }/*}}}*/
    
    /**
     * 获取所有标签
     * @param unknown $info
     * @return Ambigous <boolean, multitype:, unknown>
     */
    private function getAllTags($info){
        // 返回固定的标签
        return Tags::getTagsMap();
        $start  =   isset($info['start'])  ?   intval($info['start']) :   0;
        $length =   isset($info['length']) ?   intval($info['length']):   112;
    
        // 数据库取数据
        $tags = $this->userTagModel->getAllTags($start, $length);
        if (empty($tags)){
            return (Object) array();
        }
         
        $tmp = array();
        foreach ($tags as $val){
            $tmp = array(
                    'id'    =>    strval($val['id']),
                    'name'  =>    strval($val['name']),
                    'count' =>    strval($val['count'])
            );
            $result['tags'][] = $tmp;
        }
         
        $result['counts'] = count($result['tags']);
        return $result;
    }
    
    /**
     * 通过tag搜索用户
     * @param unknown $info
     * @return multitype:Ambigous <Ambigous, boolean, number>
     */
    private function searchUserByTag($info){
        $uid    =   AC::HOST_UID;
        $tag    =   strval($info['tag']);
        $id     =   isset($info['id'])     ?   intval($info['id'])    :   0;
        $start  =   isset($info['start'])  ?   intval($info['start']) :   0;
        $length =   isset($info['length']) ?   intval($info['length']):   AC::DIARY_LIST_DEFAULT_LEN;
        
        if (empty($info['tag'])){
            AC::$errorNo    =   'DM001';
            return  FALSE;
        }
        
        // 获取tag_id
        $tagInfo = Tags::getTagInfo($tag);
        if (empty($tagInfo)){
            return (Object) array();
        }
        $tag_id = $tagInfo['id'];
         
        $relations = $this->userTagModel->searchUserByTagName($tag, $start, $length, $id, $uid, $tag_id);
        if (empty($relations)){
            return (Object) array();            
        }
        
        // 组装返回数据
        $result = $tmp = array();
        foreach ($relations as $val){
            $tmp = $this->restructTagUsersData($uid, $val);
            if (empty($tmp)){
                continue;
            }
            $result['users'][] = $tmp;
        }

        $result['counts'] = count($result['users']);
        return $result;
    }
    
    /**
     * 组装搜索标签用户的返回列表
     * @param unknown $uid
     * @param unknown $info
     * @return multitype:|multitype:string StdClass
     */
    private function restructTagUsersData($uid, $info){
        if ($info['id'] < 1 || $info['uid'] < 1 || $info['tag_id'] < 1 ){
            return array();
        }
        
        $result = array(
                'id'    =>    '0',
                'uid'   =>    '0',
                'tag_id'=>    '0',
                'user'  =>    (Object) array()
        );
        
        isset($info['id'])    &&    $result['id']    =    strval($info['id']);
        isset($info['uid'])    &&    $result['uid']    =    strval($info['uid']);
        isset($info['tag_id'])    &&    $result['tag_id']    =    strval($info['tag_id']);
        $tmp = $this->autoUidModel->getUserInfo($info['uid']);
        $tmp = $this->autoUidModel->checkIsMe($tmp);
        $tmp['nickname']        =    $this->autoUidModel->getRemarkName($tmp);
        $tmp['is_followme']     =    $this->autoUidModel->checkUserFans($uid, $info['uid']);
        $tmp['is_mefollow']     =    $this->autoUidModel->checkUserFollow($uid, $info['uid']);
        $result['user'] = $tmp;
        
        return $result;
    }
    
    /**
     * 退出
     * @return boolean
     */
    private function signout(){
    	// 推送解绑
    	$this->jpushSetModel->setPush(array('uid'=>AC::HOST_UID,'deviceSN'=>''));
    	return TRUE;
    }
    
    // 上传表单加密secret获取API 
    private function getUploadSecret($info){
    	$platform 		 = $info['platform'];
    	$form_api_secret = AC::$upyunBucket[$info['data']['bucket']];
    	if (empty($form_api_secret)){
    		AC::$errorNo    =    'UC036';
    		return array();
    	}

        $options = array(
            "bucket"               =>  $info['data']['bucket'],
            "expiration"           =>  intval($info['data']['expiration']),
            "save-key"             =>  $info['data']['save-key'],
            "allow-file-type"      =>  $info['data']['allow-file-type'],
            "content-length-range" =>  $info['data']['content-length-range'],
            "image-width-range"    =>  $info['data']['image-width-range'],
            "image-height-range"   =>  $info['data']['image-height-range']
        );
    	$policy = base64_encode(json_encode($options));
    	$sign = md5($policy.'&'.$form_api_secret); /// 表单 API 功能的密匙（请访问又拍云管理后台的空间管理页面获取）

    	return array('policy'=>$policy, 'signature'=>$sign);
    }
    
    /**
     * 设置用户备注
     * @param unknown $userInfo
     * @param uid 为本人  fUid 为被备注的用户 nickname为备注名
     * @return boolean
     */
    private function setRmark($userInfo){
        if (intval($userInfo['uid']) < 1 || intval($userInfo['fUid']) < 1){
            AC::$errorNo    =    'UC033';
            return FALSE;
        }
        if (intval($userInfo['uid']) == intval($userInfo['fUid'])){
            AC::$errorNo    =    'UC034';
            return FALSE;
        }
        $status = $this->autoUidModel->checkUserFollow(intval($userInfo['uid']), intval($userInfo['fUid']));
        if (intval($status) < 1){
            AC::$errorNo    =    'UC035';
            return FALSE;
        }
        
        $result  =  $this->followModel->setFriendsName($userInfo);
        if (!empty(AC::$errorNo) || empty($result)){
            return  FALSE;
        }
        return TRUE;
    }

    
     // 用户相册
     private function photos($userInfo){     	
        $uid = intval($userInfo['uid']);     	
        if ($uid < 1){
            AC::$errorNo    =   'UP001';
            return  FALSE;
        }
     	
     	$start  =   0;
     	$length =   AC::PHOTOS_LIST_DEFAULT_LEN;
     	isset($userInfo['start'])    &&    $start    =    intval($userInfo['start']);
     	isset($userInfo['length'])   &&    $length   =    intval($userInfo['length']);
     	if ($start < 0)  $start  =   0;
     	
     	$access =   $this->checkAccessPremission($uid);
     	if (empty($access)){
            AC::$errorNo    =   'UP002'; // 没有查看权限
            return  FALSE;
     	} 
     	
     	$attachments = $this->diaryAttachmentModel->getDiaryImageAttachmentByUid($uid,$start,$length);
     	if(empty($attachments)){
            $attachments = (object)array();
     	}
     	$list = array();
        foreach($attachments as &$value){
            $pic = array(
                "pic_small"     => '',
                "pic_original"  => '',
                "pic_info"      => array(
                    "width"  => 0,
                    "height" => 0
                ),
                "text"      => '',
                "action"    => '',
                "uptime"    => '',
                "diaryInfo" => (object)array(),
    	    );
     
            $pirfix = AC::getProtocolUriByOS(AC::$cdn_url_img);
            $pic['pic_small']    = $pirfix.$value['attachmentPath']."!icon";
            $pic['pic_original'] = $pirfix.$value['attachmentPath'];
             		
            if(!empty($value['info'])){
                $info = explode(",", $value['info']);
                $pic['pic_info'] = array(
                    'width' => intval($info[0]),
                    'height'=> intval($info[1])
                );
            }
     		
            $diaryInfo  = $this->diaryListModel->getDiaryInfoByBodyId($value['bodyId']);
            if(!empty($diaryInfo)){
                $pic['diaryInfo'] = $diaryInfo;
                $pic['text'] =  $diaryInfo['abbreviation'];
            }
           			
            $pic['action'] =  "pinksns://diary/info?uid={$value['uid']}&bodyId={$value['bodyId']}";
            $pic['uptime'] = $value['uploadTime'];
            $list[] = $pic;
    	}  
		
        $result = $this->restructDiaryPhotosData($list,$uid);		
        return $result;     	
    }
    
    private function restructDiaryPhotosData($list,$uid){			
        $data = array(
        	'title_top'    => "用户相册",
        	'pics'         => (object)array(),
        	'counts'       => "0",
        	'total_counts' => "0"
        );
    		
    	isset($list) && $data['pics'] = $list;
    	isset($list) && $data['counts'] = strval(count($list));
    	$data['total_counts'] = $this->diaryAttachmentModel->getDiaryImageAttachmentByUidCount($uid);
    	return $data;    	
     }


    public function getHighQualitySubscription($param)
	{
	    return $this->getSubscriptionList($param);
//		if($param['id']>0){
//			return array();
//		}
//		$id = 0;
//		$uid = $param['uid'];
//		$length = 10;
//		$result = $this->diaryListCacheModel->getHighQualitySubscription($id,$length);
////		$result = array('8','21119999','22679212','22003398','21958212','21849100');
//		if(!$result) return array();
//
//		foreach($result as $val){
//			$recuser = $this->rebuildData(array('uid'=>$val,'id'=>$val));
//			$recuser['is_followme']      = $this->autoUidModel->checkUserFans($uid, $val);
//			$recuser['is_mefollow']      = $this->autoUidModel->checkUserFollow($uid, $val);
//			$recuser['user']['is_followme']      = $this->autoUidModel->checkUserFans($uid, $val);
//			$recuser['user']['is_mefollow']      = $this->autoUidModel->checkUserFollow($uid, $val);
//			$users[] 		= $recuser;
//		}
//
//		$res = array(
//			'users' => $users,
//			'counts'=> count($users)
//		);
//		return $res;
	}
	/**
	 * 订阅号
	 * @param $param
	 */
	public function getSubscriptionList($param)
	{
		$userId = $param['uid'];
		$length = 20;
        //根据id获取达人信息
        $start = 0;
        if($param['id']) {
            $userAbility = $this->userModel->getAbility($param['id']);
            if(!$userAbility) return (object)array();
            $lastUid = $userAbility[0]['uid'];
            $lastKey = $this->diaryListCacheModel->getSubscriptionRank($lastUid);
            if($lastKey){
                $start = $lastKey + 1;
            }
        }
        $start<0 && $start = 0;
        //查找redis排序列表
        $result = $this->diaryListCacheModel->getSubscriptionCache($start, $length);

        if(!$result) return (object)array();
        $users = [];
        foreach ($result as $uid => $sort) {
            $ability = $this->userModel->fetchAbility(array('uid' => $uid));
            $recuser = $this->rebuildData(['id' => $ability[0]['id'], 'uid' => strval($uid)]);
            $recuser['is_followme'] = $this->autoUidModel->checkUserFans($userId, $uid);
            $recuser['is_mefollow'] = $this->autoUidModel->checkUserFollow($userId, $uid);
            $recuser['user']['is_followme'] = $this->autoUidModel->checkUserFans($userId, $uid);
            $recuser['user']['is_mefollow'] = $this->autoUidModel->checkUserFollow($userId, $uid);
            $users[] = $recuser;
        }

		$res = array(
			'users' => $users,
			'counts'=> count($users)
		);
		return $res;
	}

	public function importDataToRedis(){
        $start = 0;
        $db_length = 20;
        $i = 10000;
        $this->diaryListCacheModel->delSubscription();
        while ($result_tmp = $this->userModel->getVerifiedAbility($start,$db_length)) {
            foreach ($result_tmp as $value) {
                if (empty($value['uid'])) continue;
                $cache = $this->diaryListCacheModel->findSubscription($value['uid']);
                if ($cache) continue;
                $this->diaryListCacheModel->setSubscriptionUids($value['uid'], $i);
                $i--;
                $start = $value['id'];
            }
        }
        return true;
    }

	public function rebuildData($info)
	{
		$uid = $info['uid'];
		$recuser['id'] = $info['id'];
		$userInfo 	   				= $this->autoUidModel->getUserInfo($uid);
		$recuser['uid']				= $uid;
		$recuser['nickname']		= $this->autoUidModel->getRemarkName($userInfo);
		$recuser['avatar']			= $userInfo['avatar'];
		$recuser['signature']		= $userInfo['signature'];
		$recuser['user']            = $this->autoUidModel->checkIsMe($userInfo);
		$recuser['user']['nickname']= $recuser['nickname'];
		return $recuser;
	}
    # 名人堂 start
    /**
     * 申请达人,必须条件:
     * uid,label
     * uc051 申请达人资料不全
     * UIM024 申请人信息错误
     * @param unknown $userInfo
     * @return boolean|Ambigous <boolean, unknown>
     */
    public function applyAbility($userInfo){
        if (intval($userInfo['uid']) < 1 || empty($userInfo['label'])){
            AC::$errorNo = 'UC051';
            return FALSE;
        }
        // 默认内容
        if (empty($userInfo['content'])){
            $userInfo['content']    =    '更好的营造我最喜欢的粉粉日记,让更多人喜欢她!';
        }
        // 默认状态
        if (empty($userInfo['status'])) {
            $userInfo['status']     =    '0';
        }
        $uid   =  intval($userInfo['uid']);
        $info  =  $this->autoUidModel->getUserInfo($uid,'1');
        $userCount = $this->userStatisticsModel->getUserStatistics(array('uid' => $uid));
        $info['followMes_count'] = $userCount['followMeTimes'];
        
        $info['content']    =    $userInfo['content'];
        $info['status']     =    $userInfo['status'];
        $info['uid']        =    $uid;
        $info['label']      =    $userInfo['label'];
        // 已经拒绝或者过期的达人使用更新策略
        $abilityInfo = $this->userModel->fetchAbility(array('uid'=>$uid));
        
        if (empty($abilityInfo)){
            $result = $this->userModel->addAbility($info);
        }else{
            $result = $this->userModel->setAbility($info);
        }
        if (!$result) return false;
        
        $this->diaryListCacheModel->delUserCache($uid);
        return TRUE;
    }
    
    /**
     * 达人申请条件
     * @param unknown $info
     * @return boolean|multitype:string
     */
    public function abilityCondition($info){
        $uid      = intval($info['uid']);
        $host_uid = AC::HOST_UID;
        if (empty($uid) || empty($host_uid) || ($uid != $host_uid)){
            return FALSE;
        }
        
        $userInfo = $this->autoUidModel->getUserInfo($uid, true);
        $avatar   = $this->userLoginModel->getUserImage($userInfo);
        $userCount = $this->userStatisticsModel->getUserStatistics($userInfo);
        
        $condition = array(
            'avatar'        =>  intval($avatar['image']) > 0 ? '1' : '0',
            'diary_limit'   =>  $userCount['diaryTimes'],
            'fans_limit'    =>  $userCount['followMeTimes'],
            'level'         =>  $userInfo['level']
        );
        
        $list  = array();
        $list['condition'][] = $this->checkAvatarCondition($condition); 
        $list['condition'][] = $this->checkLevelCondition($condition);
        $list['condition'][] = $this->checkFansCondition($condition);
        $list['condition'][] = $this->checkDiarysCondition($condition);

        $list['infos']  =   $this->checkStatusCondition($info);
        
        return $list;
    }
    
    public function countLevelExp ($userInfo, $isadmin = false)/*{{{*/
    {
        $log = "";
        if (empty($userInfo['uid'])) {
            AC::$errorNo = 'UC011';
            return FALSE;
        }
        if (empty($userInfo['profitType']) || empty($userInfo['profitTimes'])) {
            AC::$errorNo = 'UC024';
            return FALSE;
        }
        $member = $this->userMemberModel->getMemberInfo($userInfo, true);
        if (empty($member['uid'])) {
            AC::$errorNo = 'UC025';
            return FALSE;
        }
       
        $profitInfo = NULL;
        $nextLevelExp = ExpLevel::$levelNeedExp[$member['level']];
        $today = date('md', AC::SERVER_TIME);
        $data = array();
        if ($today != $member['profitDay']) {
            $data['uid'] = $userInfo['uid'];
            $data['profitDay'] = $today;
            $data['diaryTimes'] = 0;
            $data['commentTimes'] = 0;
            $data['likeTimes'] = 0;
            $data['likedTimes'] = 0;
            $data['diaryTagTimes'] = 0;
            
            // today exp
            
            // group
            $data['addTopicTimes'] = 0;
            $data['postTopicCommentTimes'] = 0;
            // 转发以及被转发
            $data['repostTimes'] = 0;
            $data['repostedTimes'] = 0;
            // 初始化
            $data['todayExp'] = 0;
            $data['privateDiary'] = 0;
            $data['deleteDiary'] = 0;
            $data['deleteDiaryByadmin'] = 0;
            $data['deleteCommentByadmin'] = 0;
            $data['deleteTopic'] = 0; // 话题删除
            $data['deleteTopicByadmin'] = 0; // 话题删除
            $data['forbidUser'] = 0; // 被封禁减少50%经验
            $data['gagUser1'] = 0; // 第1次禁言
            $data['gagUser2'] = 0; // 第2次禁言
            $data['gagUser3'] = 0; // 第3次禁言
            
            $data['level'] = $member['level'];
            
            if ($userInfo['profit'] < 0) {
                // 经验减少
                $reduce = $this->reduceUserExp($member, $userInfo['profit']);
                $data['level'] = $reduce['level'];
                $data['exp'] = $reduce['exp'];
                $data[$userInfo['profitType']] = 1;
                $profitInfo['gainExp'] = $userInfo['profit'];
            } else {
                $todayExp = $userInfo['profit'];
                $vip_info = $this->autoUidModel->getUserVipInfo($userInfo['uid']);
                $dayMaxExp = ExpLevel::$typeGainTimes['dayMaxExp'];
                /*if ($vip_info){
                    $tmp_uptimes = $vip_info['is_year_vip'] ? AC::VIP_YEAR_EXP_ADDED_TIMES : AC::VIP_EXP_ADDED_TIMES;
                    $dayMaxExp = ceil( $dayMaxExp * $tmp_uptimes );
                }*/
                if ($todayExp <= $dayMaxExp ||
                         $isadmin) {
                    if ($vip_info && AC::$allowVipExpAdded){
                        //经验加成
                        if ($vip_info['is_year_vip']){//年费会员加成1.5倍
                            $todayExp = $userInfo['profit'] = ceil($userInfo['profit'] * AC::VIP_YEAR_EXP_ADDED_TIMES);
                        }else{//普通会员加成1.2倍
                            $todayExp = $userInfo['profit'] = ceil($userInfo['profit'] * AC::VIP_EXP_ADDED_TIMES);
                        }
                    }
                    $data['exp'] = $member['exp'] + $userInfo['profit'];
                    $data['todayExp'] = $todayExp;

                    // 经验增加
                    $profitInfo['gainExp'] = $userInfo['profit'];

                    if ($member['exp'] + $userInfo['profit'] >= $nextLevelExp) {
                        $data['level'] ++;
                        $data['exp'] = $member['exp'] + $userInfo['profit'] -
                        $nextLevelExp;
                        $profitInfo['newLevel'] = $data['level'];
                    }
                    $data[$userInfo['profitType']] = 1;
                }
            }
            
        } else {
            if ($member[$userInfo['profitType']] < $userInfo['profitTimes']) {
                
                $data['uid'] = $userInfo['uid'];
                $data['todayExp'] = $member['todayExp'];
                $data['privateDiary'] = $member['privateDiary'];
                $data['deleteDiary'] = $member['deleteDiary'];
                $data['deleteDiaryByadmin'] = $member['deleteDiaryByadmin'];
                $data['deleteCommentByadmin'] = $member['deleteCommentByadmin'];
                $data['deleteTopic'] = $member['deleteTopic']; // 话题删除
                $data['deleteTopicByadmin'] = $member['deleteTopicByadmin']; // 话题删除
                $data['forbidUser'] = $member['forbidUser']; // 被封禁减少50%经验
                $data['gagUser1'] = $member['gagUser1']; // 第1次禁言
                $data['gagUser2'] = $member['gagUser2']; // 第2次禁言
                $data['gagUser3'] = $member['gagUser3']; // 第3次禁言
                
                $data[$userInfo['profitType']] = $member[$userInfo['profitType']] +
                         1;
                $data['level'] = $member['level'];

                if ($userInfo['profit']< 0) {
                    // 经验减少
                    $reduce = $this->reduceUserExp($member,  $userInfo['profit']);
                    $profitInfo['gainExp'] = $userInfo['profit'];
                    $data['level'] = $reduce['level'];
                    $data['exp'] = $reduce['exp'];
                } else {
                    // 经验增加
                    $todayExp = $member['todayExp'] + $userInfo['profit'];
                    $vip_info = $this->autoUidModel->getUserVipInfo($userInfo['uid']);
                    $dayMaxExp = ExpLevel::$typeGainTimes['dayMaxExp'];
                    /*if ($vip_info){
                        $tmp_uptimes = $vip_info['is_year_vip'] ? AC::VIP_YEAR_EXP_ADDED_TIMES : AC::VIP_EXP_ADDED_TIMES;
                        $dayMaxExp = ceil( $dayMaxExp * $tmp_uptimes );
                    }*/
                    if ($todayExp <= $dayMaxExp ||
                             $isadmin) {
                        if ($vip_info && AC::$allowVipExpAdded){
                            //经验加成
                            if ($vip_info['is_year_vip']){//年费会员加成1.5倍
                                $todayExp = ceil($todayExp * AC::VIP_YEAR_EXP_ADDED_TIMES);
                                $userInfo['profit'] = ceil($userInfo['profit'] * AC::VIP_YEAR_EXP_ADDED_TIMES);
                            }else{//普通会员加成1.2倍
                                $todayExp = ceil($todayExp * AC::VIP_EXP_ADDED_TIMES);
                                $userInfo['profit'] = ceil($userInfo['profit'] * AC::VIP_EXP_ADDED_TIMES);
                            }
                        }
                        $profitInfo['gainExp'] = $userInfo['profit'];
                        $data['exp'] = $member['exp'] + $userInfo['profit'];
                        $data['todayExp'] = $todayExp;
                        
                        if ($member['exp'] + $profitInfo['gainExp'] >= $nextLevelExp) {
                            $data['level'] ++;
                            $data['exp'] = $member['exp'] + $userInfo['profit'] -
                            $nextLevelExp;
                            $profitInfo['newLevel'] = $data['level'];
                        }
                    }
                }
            }
        }
        if ($data['todayExp'] < 0) {
            $data['todayExp'] = 0;
        }
        
        if (! empty($profitInfo['newLevel'])) {
            // 升级了将用户缓存删除
            $this->diaryListCacheModel->delUserCache($userInfo['uid']);
            
            if (! empty(ExpLevel::$levelMapFlow[$profitInfo['newLevel']])) {
                $data['allTraffic'] = ExpLevel::$levelMapFlow[$profitInfo['newLevel']] *
                         1024;
                $profitInfo['allTraffic'] = $data['allTraffic'];
            }
            if (! empty(ExpLevel::$levelAddFlow[$profitInfo['newLevel']])) {
                $data['traffic'] = ExpLevel::$levelAddFlow[$profitInfo['newLevel']] *
                         1024 + $member['traffic'];
                if ($data['traffic'] > $data['allTraffic']) {
                    $data['traffic'] = $data['allTraffic'];
                }
            }
            if (! empty(ExpLevel::$levelMapFollow[$profitInfo['newLevel']])) {
                $profitInfo['followNums'] = ExpLevel::$levelMapFollow[$profitInfo['newLevel']];
            }
        }
        if (! empty($data)) {
            $this->userMemberModel->setMemberInfo($data, true);
        }
  
        if (! empty($data)) {
            //set log
            //[时间][管理员操作][用户UID][动作][规则每日限制次数][经验数值][提示经验数值][升级数据][等级数据]
            $log = $log."[".date('m-d H:i:s', AC::SERVER_TIME)."]";
            if($isadmin){
                $log = $log."[1]";
            }else{
                $log = $log."[0]";
            }
            $log = $log."[".$userInfo['uid']."]";//uid
            $log = $log."[".$userInfo['profitType']."]";//profitType
            $log = $log."[".$userInfo['profitTimes']."]";//profitType
            $log = $log."[".$userInfo['profit']."]";//profit
            $log = $log."[".$profitInfo['gainExp']."]";//profit
            if($profitInfo['newLevel']){
                $log = $log."[".$profitInfo['gainExp']."]";//profit
            }else{
                $log = $log."[]";//profit
            }
            if($data['level']){
                $log = $log."[level=".$data['level'].",exp=".$data['exp']."]";//profit
            }else{
                $log = $log."[]";//profit
            }
             $log = $log."\n";//profit
            UK::saveLog('exp.log', $log,  TRUE);
        }
        return $profitInfo;
    }

    /**
     * 减少用户经验值
     */
    private function reduceUserExp ($member, $exp)
    {
       
        $total = $this->getTotalExp($member['level'], $member['exp']);
        
        // 加减经验值
        if ($exp > - 1 && $exp < 0) {
            $total = $total + ($total * $exp);
        } else {
            $total = $total + $exp;
        }
        $result = array();
        $result['level'] = 1;
        $result['exp'] = 0;
        
        if ($total <= 0) {
            return $result;
        }
        $result = $this->getLevel($total);
        return $result;
    }

    private function getLevel ($total)
    {
        $result = array();
        $result['level'] = 1;
        $result['exp'] = 0;
        
        if ($total <= 0) {
            return $result;
        }
        
        for ($l = 1; $l < 60; $l ++) {
            $exp1 = intval(ExpLevel::$levelNeedExp[$l]); // 60
            if ($total < $exp1) {
                $result['level'] = $l;
                $result['exp'] = $total;
                break;
            }
            $total = $total - $exp1;
        }
        return $result;
    }

    function getTotalExp ($level, $exp)
    {
        $total = $exp;
    
        if ($level > 0) {
            for ($l = 1; $l < $level; $l ++) {
                $l_exp = intval(ExpLevel::$levelNeedExp[$l]);
                if ($l_exp > 0) {
                    $total = $total + $l_exp;
                }
            }
        }
        return $total;
    }

    private function checkPrivateEmail($email)/*{{{*/
    {
        $email  =   trim($email);
        $email  =   strtolower($email);
        $privateEmail   =   array(
                                'xxtstudio@163.com' =>  1, 
                                SERVICE_MAIL_ADDR =>  1,
                            );
        if (empty($privateEmail[$email]))   return  TRUE;
        return  FALSE;
    }/*}}}*/

    private function checkNickname($nickname)/*{{{*/
    {
        $limitNickname  =   array(
                                '粉粉社区',
                                '粉粉日记',
                                '管理员',
                                '上海盘隆',
                            );
        $result =   str_replace($limitNickname, '***', $nickname);
        // 限制用户昵称,24个字符,不能有空格
        $result   =  UK::getstr($result, '24');
        
        return  $result;
    }/*}}}*/

    private function checkDeviceStatus($deviceSN, $loginInfo = NULL)/*{{{*/
    {
        if (empty($deviceSN))
        {
            AC::$errorNo    =   'UC016';
            return  FALSE;
        }
        $forbid =   $this->forbidDeviceModel->getForbidDeviceInfo(array('deviceSN'  =>  $deviceSN));
        if (!empty($forbid['status']))
        {
            // 登录信息加如数据库
            if (!empty($loginInfo)){
                $this->forbidDeviceModel->addForbidDeviceLogin($loginInfo);
            }
            $string =   AC::$errorNo. ' : '. date('Y-m-d H:i:s', AC::SERVER_TIME). ' : '. DOP::encodeData($forbid). ' : '. DOP::encodeData($loginInfo). "\r\n";
            UK::saveLog('forbidDevice.log', $string, TRUE);
            AC::$errorNo    =   'UC017';
            return  FALSE;
        }
        return  TRUE;
    }/*}}}*/

    private function checkAccessPremission($uid)/*{{{*/
    {
        if ((AC::HOST_UID   ==  $uid))  return  TRUE;

        $array      =   array('uid' => AC::HOST_UID, 'fUid' => $uid, 'alarm' => TRUE);
        $isBlackMe  =   $this->followModel->isBlackMe($array);
        if (empty($isBlackMe))  return  TRUE;

        return  FALSE;
    }/*}}}*/
    // 发送私信
    private function sendMessage($info){
        // 发送私信,有待查看如何发送
        $user = $this->autoUidModel->getUserInfo($info['uid']);
        $messageModel = new MessageBoxModel();
        $param = array(
                'uid'      => '1',
                'mUid'     => $info['uid'],
                'nickname' => '粉粉小秘书',
                'mNickname'=> $user['nickname'],
                'content'  => $info['content'],
        );
        $messageModel->sendAbilityMessage($param);
    }
    
    // 判断是否再次申请条件
    private function checkStatusCondition($info){
        $ability_info   =   $this->userModel->fetchAbility($info);
        if (empty($ability_info)){
            return (Object) array();
        }
        $ability  = $ability_info[0];
        $condition = FALSE;
        if ((AC::SERVER_TIME - intval($ability['dateline'])) > AC::ABILITY_TIME){
            $condition = TRUE;
        }
        if ($ability['status'] == 2 && $condition){
            $ability['status']  = '3';
        }
        return $ability;
    }
    // 判断头像条件
    private function checkAvatarCondition($info){
        $data = array();
        $data['name']  = 'avatar';
        $data['title'] = '上传清晰头像';
        $data['result']= '1';
        if ($info['avatar'] != AC::ABILITY_AVATAR){
            $data['title'] = '上传清晰头像';
            $data['result']= '0';
        }
        return $data;
    }
    // 判断粉丝条件
    private function checkLevelCondition($info){
        $data = array();
        $data['name']  = 'level_limit';
        $data['title'] = '等级达到12级';
        $data['result']= '1';
        if ($info['level'] < AC::ABILITY_LEVEL_LIMIT){
            $data['title'] = '等级达到12级';
            $data['result']= '0';
        }
        return $data;
    }
    // 判断粉丝条件
    private function checkFansCondition($info){
        $data = array();
        $data['name']  = 'fans_limit';
        $data['title'] = '粉丝数超过50人';
        $data['result']= '1';
        if ($info['fans_limit'] < AC::ABILITY_FANS_LIMIT){
            $data['title'] = '粉丝数超过50人';
            $data['result']= '0';
        }
        return $data;
    }
    // 判断粉丝条件
    private function checkDiarysCondition($info){
        $data = array();
        $data['name']  = 'diarys_limit';
        $data['title'] = '分享日记超过50篇';
        $data['result']= '1';
        if ($info['diary_limit'] < AC::ABILITY_DIARYS_LIMIT){
            $data['title'] = '分享日记超过50篇';
            $data['result']= '0';
        }
        return $data;
    }
    // 修改用户信息
    private function editUserBaseInfo($userInfo){
        // 用户昵称不能为空，不能是空格，不能是换行等
    	if(isset($userInfo['nickname'])){
            $userInfo['nickname'] = UK::getstr($userInfo['nickname'], 24, '', 1);
            $userInfo['nickname'] = UK::replaceNickname($userInfo['nickname'], $userInfo['uid']);
            if(strlen($userInfo['nickname']) < 1){
                AC::$errorNo    =   'UC006';
                return  FALSE;
            }
    	}
       
    	if (isset($userInfo['email']))
    	{
            $userInfo['email'] = UK::getstr($userInfo['email'], 64, '', 1);
            if(strlen($userInfo['email']) < 1){
                AC::$errorNo    =   'UC005';
                return  FALSE;
            }
    	}
    	
        // 是否禁言
        $status  =  $this->autoUidModel->checkUserStatus(AC::$hostUserBaseInfo);
        if (!empty(AC::$errorNo)){
            return  FALSE;
        }
	
        if (AC::$hostUserBaseInfo['uid'] != $userInfo['uid'])
        {
            AC::$errorNo    =   'UC010';
            return  FALSE;
        }
        
        $user               =   $this->userModel->getUserInfo($userInfo['uid']);
        // 删除用户缓存
        $this->diaryListCacheModel->delUserCache($userInfo['uid']);
        
        if (isset($userInfo['nickname']))   $userInfo['nickname']   =   $this->checkNickname($userInfo['nickname']);
        
        $userInfo['account']=   AC::$hostUserBaseInfo['account'];
        if (isset($userInfo['nickname'])    &&  ($userInfo['nickname']  === AC::$hostUserBaseInfo['nickname'])){
            unset($userInfo['nickname']);
        }
        if (isset($userInfo['email'])       &&  ($userInfo['email']     === AC::$hostUserBaseInfo['email'])){
            unset($userInfo['email']);
        }
        if (isset($userInfo['nickname']) || isset($userInfo['email'])){
            $userResutlt = $this->autoUidModel->setUserInfo($userInfo);
            if (!$userResutlt){
                return FALSE;
            }
        }
        
        // 修改头像
        $image  = array();
        $photo  = array();
        isset($userInfo['image'])    &&    $image    =    array($userInfo['image']);
        isset($userInfo['photos'])   &&    $photo    =    $userInfo['photos'];
        if (!isset($userInfo['photos']) && !empty($user['photos'])){
            $photo = json_decode($user['photos'],true);
        }
        
        if (!empty($image)){
            $userInfo['photos'] = array_merge($image, $photo);
        }
        
        if(is_array($userInfo['photos']) && count($userInfo['photos']) > 0){
            $photos = array();
            foreach($userInfo['photos'] as $photo){
                $check = UK::check_upyun_node(AC::HOST_UID, AC::$hostUserBaseInfo['account'], $photo);
            	if($check){
            	    $photos[] = $photo;
            	}  
            }
            
            $photos = array_slice($photos, 0, 8);
            $userInfo['image']  =  $photos[0]; // 将相册的第一张设置为图像
            $userInfo['photos'] =   json_encode($photos);
       	}
       	 
        $this->userLoginModel->setUserInfo($userInfo);
        if($user['sex'] == AC::$sex['femaleauth']){//女生认证过
            unset($userInfo['sex']);
        }
        
        $this->userModel->setUserInfo($userInfo);
        
        return TRUE;
    }
    
    /**
     * 用户账号绑定
     * @param unknown $info
     * @return boolean
     */
    public function accountBind($info){
    	$account   = UK::getstr($info['account'],24);
    	$type      = UK::getstr($info['type'],24);
    	$passwd    = UK::getstr($info['passwd'],32);
    	$extra     = UK::getstr($info['extra'],520);
    	$uid       = AC::HOST_UID;
    	 
    	if ( empty($account) || empty($passwd) || empty($type) || empty($uid) ) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
    	}
    
    	$useInfo = $this->autoUidModel->getUserInfo($uid);
    	if (empty($useInfo)) return false;
        
    	// 账号类型校验
    	$check = $this->checkBindTypeIsNotEqualToAccountType($type, $useInfo['account']);
    	if (!$check) {
    	    UK::varDump(AC::$errorNo, __METHOD__);
    	    return FALSE;
    	}
    	
    	// 不能绑定两个同类型账号
    	$userConnects = $this->getUserConnects();
    	
    	$bind_type = UK::getAccountBindTypeOrOpenType($type);
    	if ($userConnects[$type]) {
    	    AC::$errorNo    =   'UB033';
    	    return FALSE;
    	}
    	
    	$result =  $this->bindAccountByType($bind_type, $account, $passwd, $useInfo, $extra, $userConnects);
    	if ($result) {
    	    $this->addAccountBindOrUnbindLog($uid, 'accountbind', $useInfo['account'], $info);
    	}
    	
    	return $result;
    }
    
    private function bindAccountByType ($bind_type, $account, $passwd, $useInfo, $extra, $userConnects) {
        switch ($bind_type){
            case AC::ACCOUNT_TYPE_FENFEN_ACCOUNT:
                $result = $this->fenfenBind($account, $passwd, $useInfo, $extra, $userConnects);
                break;
            case AC::ACCOUNT_TYPE_MOBILE:
                $result = $this->userMobileBind($account, $passwd, $useInfo, $extra, $userConnects);
                break;
            default:
                $result = $this->openUidBind($account, $extra, $bind_type, $useInfo);
                break;
        }
        
        return $result;
    }
    
    private function checkBindTypeIsNotEqualToAccountType ($type, $account) {
        $bind_type = UK::getAccountBindTypeOrOpenType($type);
        if (empty($bind_type)) {
            AC::$errorNo    =   'UB011';
            return FALSE;
        }
        
        $account_type = UK::getAccountTpye($account);
        if($account_type == $bind_type){
            AC::$errorNo    =   'UB099';
            return FALSE;
        }
        
        return true;
    }
    
    private function getUserConnects () {
        $userConnects = $this->getConnent();
        if (empty($userConnects)) return $userConnects;
        
        $result = array();
        foreach ($userConnects['connents'] as $val) {
            $result[$val['type']] = $val;
        }
        
        return $result;
    }
    
    /**
     * 粉粉账号绑定
     * @param unknown $username
     * @param unknown $passwd
     * @param unknown $info
     * @param unknown $extra
     * @param unknown $userConnects
     * @return boolean
     */
    private function fenfenBind($username, $passwd, $info,  $extra, $userConnects){
        // 校验用户名是否合法
    	if(UK::getAccountTpye($username) != AC::ACCOUNT_TYPE_FENFEN_ACCOUNT){
            AC::$errorNo    =   'UB010';
            return FALSE;
    	}
    	
    	// 查询绑定的账号是否存在
    	$result = $this->userLoginModel->getUserInfoByAccount($username);
    	if(!empty($result)){
            AC::$errorNo    =   'UB022';
            return FALSE;
    	}
    	
    	// 如果有手机账号，必须验证密码(保持粉粉登陆和手机登陆密码一致)
    	$mobileConnect = $userConnects[UK::getAccountBindTypeOrOpenType(AC::ACCOUNT_TYPE_MOBILE, true)];
    	if ($mobileConnect) {
    	    $mobileConnectAccont = UK::getMobileUser($mobileConnect['account']);
    	    $userLoginInfo = $this->userLoginModel->getUserInfoByAccount($mobileConnectAccont);
    	    if ( $userLoginInfo &&  ($userLoginInfo['passwd'] != UK::cryptPasswd($mobileConnectAccont, $passwd))) {
    	        AC::$errorNo  = 'UB027';
    	        return FALSE;
    	    }
    	}
        
    	// 粉粉账号绑定，修改邮箱
    	$extraInfo = UK::parse_query($extra);
    	if ($extraInfo['email']) {
    	    $emailInfo = array('email' => $extraInfo['email'], 'uid' => $info['uid'], 'account' => AC::$hostUserBaseInfo['account']);
    	    $editUserBaseInfo = $this->editUserBaseInfo($emailInfo);
    	    if (!$editUserBaseInfo) {
    	        UK::varDump(AC::$errorNo, __METHOD__);
    	        return  FALSE;
    	    }
    	}
    	
    	// 初始化数据库
    	$param = array(
    	    'open_type'        =>  AC::ACCOUNT_TYPE_FENFEN_ACCOUNT,
    	    'connent_type'     =>  1,
    	    'uid'              =>  $info['uid'],
    	    'account'          =>  $username,
    	    'type'             =>  AC::ACCOUNT_TYPE_FENFEN_ACCOUNT,
    	    'nickname'         =>  $info['nickname'],
    	    'passwd'           =>  $passwd
    	);
    	
    	$result = $this->initUserLoginAndConnect($param);
    	if (empty($result)) {
    	    UK::varDump(AC::$errorNo, __METHOD__);
    	    return  false;
    	}
    	
    	return true;
    }
    
    /**
     * 手机号绑定
     * @param unknown $mobile
     * @param unknown $passwd
     * @param unknown $code
     * @return boolean
     */
    private function userMobileBind($mobile, $passwd, $useInfo, $extra, $userConnects){
        if (empty($mobile) || empty($passwd) || empty($useInfo) || empty($extra) ) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }
        
        $uid        = intval($useInfo['uid']);
        $extras     = UK::parse_query($extra);
        $code       = $extras['code'];
        $nickname   = $extras['nickname'];
        $platform   = 'mobile';

        if (AC::$fixPasswdVersion && isset($extras['open_token'])) {
            $passwd = $extras['open_token'];
        }

        // 手机注册，不能再绑定手机号
        $userLoginInfo = $this->userLoginModel->getUserInfoByAccount($useInfo['account']);
        if ($userLoginInfo['type'] == AC::ACCOUNT_TYPE_MOBILE) {
            AC::$errorNo  = 'UB026';
            return FALSE;
        }
        
        // 获取新绑定账号是否存在
        $account   =  UK::getMobileUser($mobile);
        $result = $this->userLoginModel->getUserInfoByAccount($account);
        if($result){
            AC::$errorNo  = 'UB025';
            return FALSE;
        }

        // 判断验证码
        $mobileCodeIsValid = $this->autoUidModel->checkMobileCodeIsValid($mobile, $code, UK::getMobileCodeType('mobile_bind'));
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        // 验证密码(如果是粉粉账号登陆，必要，保持粉粉登陆和手机登陆密码一致)
        $fenfenConnect = $userConnects[UK::getAccountBindTypeOrOpenType(AC::ACCOUNT_TYPE_FENFEN_ACCOUNT, true)];
        if ($fenfenConnect) {
            $userLoginInfo = $this->userLoginModel->getUserInfoByAccount($fenfenConnect['account']);
            $cryptPasswd = UK::cryptPasswd($fenfenConnect['account'], $passwd);
            if ( $userLoginInfo &&  ($userLoginInfo['passwd'] != $cryptPasswd)) {
                AC::$errorNo  = 'UB027';
                return FALSE;
            }
        }
        
        
        // 初始化数据库
        $param = array(
            'uid'           =>  $uid,
            'account'       =>  $account,
            'type'          =>  AC::ACCOUNT_TYPE_MOBILE,
            'nickname'      =>  $nickname,
            'passwd'        =>  $passwd,
            'open_type'     =>  AC::ACCOUNT_TYPE_MOBILE,
            'connent_type'  =>   0,
            'open_token'    =>   $passwd,
            'extra'         =>   UK::JsonFormat($extras)
        );
         
        $result = $this->initUserLoginAndConnect($param);
        if (empty($result)) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  false;
        }
        
        return true;
    }
    
    private function checkMobileAccountIsExisted ($mobile) {
        $result = $this->userLoginModel->getUserInfoByAccount($mobile);
        if ($result) return true;
        
        $account   =  UK::getMobileUser($mobile);
        $result = $this->userLoginModel->getUserInfoByAccount($account);
        if($result) return true;
        
        return false;
    }
    
    /**
     * 发送手机验证码
     */
    public function getMobileCode($info) {
        $uid    = AC::HOST_UID;
        $mobile = $info['mobile'];
        $type   = $info['type'];
        $appname = isset($info['appname']) ? strval($info['appname']) : '粉粉日记';
        if (empty($mobile) || empty($type)) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }
        
        // 验证传参
        $isMobile   = UK::isMobile($mobile);
        $codeType   = UK::getMobileCodeType($type);
        if (!$isMobile || !$codeType) {
            AC::$errorNo  =   'UC020';
            return  FALSE;
        }
        
        // 修改密码需要查询账号是否存在
        $mobileExisted = $this->checkMobileAccountIsExisted($mobile);
        if ($type === "mobile_signup" && !$mobileExisted) {
            AC::$errorNo  =   'UC030';
            return  FALSE;
        }

        if (in_array($type, array("mobile_register", "mobile_bind", "mobile_update")) && $mobileExisted) {
            AC::$errorNo  =   'UC027';
            return  FALSE;
        }
        
        if ($type === "mobile_resetpasswd" && !$mobileExisted) {
            AC::$errorNo  =   'UC026';
            return  FALSE;
        }

        //提现相关需要传入提现账号
        $accountNo = $info['accountNo'];
        if ($type === "mobile_withdrawal" && (!$mobileExisted || !$accountNo)) {
            AC::$errorNo  =   'UC032';
            return  FALSE;
        }

        if ($type === "mobile_setwithdrawal" && (!$mobileExisted || !$accountNo)) {
            AC::$errorNo  =   'UC033';
            return  FALSE;
        }
        
        // 验证码每小时只能发送 CODENUMPERHOUR 次，需要定时清理code表数据
        $codes = $this->autoUidModel->getMobileCodes(UK::getClientIp());
        if ($codes && !in_array($appname, ['可萌记账'])) {
            if ((AC::SERVER_TIME - AC::ONEMINUTE) < $codes[0]['time']) {
                AC::$errorNo  =   'UC028';
                AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            }
            
            if ((AC::SERVER_TIME - AC::ONEHOUR) < $codes[AC::CODENUMPERHOUR - 1]['time']) {
                AC::$errorNo  =   'UC029';
                AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            }

            if ((AC::SERVER_TIME - AC::ONEDAY) < $codes[AC::CODENUMDAILY - 1]['time']) {
                AC::$errorNo  =   'UC031';
                AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            }
            if (AC::$errorNo) return  FALSE;
        }
        
        // 生成新的验证码
        $newCode = UK::generateCode(6);
        $result = $this->autoUidModel->addMobileCode($mobile, $codeType, $newCode, $uid);
        if (!$result) return false;
        
        // 发短信
        $mobileInfo = explode('-', $mobile);
        $msg = "验证码为 $newCode ,有效时间30分钟，希望你在".$appname."里玩耍愉快！【".$appname."】";
        if ($type === "mobile_resetpasswd") {
            $msg = "验证码为 $newCode ,你正在修改账户信息，有效时间30分钟，请勿告知他人哟～【".$appname."】";
        }elseif ($type === "mobile_signin" && !$mobileExisted){
            $msg = "验证码 $newCode ,不要告诉别人呐！密码 $newCode 是登录粉粉日记app的哦~忘记密码，随时召唤么么哒~【".$appname."】";
            $this->initMobileUser($mobile, $newCode);
        }elseif ($type === "mobile_withdrawal" || $type === "mobile_setwithdrawal"){
            $accountNo = substr_replace($accountNo, '****', '3', '4');
            $msg = "输入验证码 $newCode ,确认 $accountNo 为您的支付宝账户，如非本人操作请忽略。【".$appname."】";
            $this->initMobileUser($mobile, $newCode);
        }
        
        $this->autoUidModel->sendShortMessage(array('code' => $newCode, 'mobile' => $mobileInfo[1], 'content' => $msg, 'appname' => $appname));
        
        return true;
    }

    /**
     * 初始化用户
     * @param $mobile
     * @param $newCode
     * @return bool
     */
    private function initMobileUser($mobile, $newCode)
    {
        $account  = 'mobile-'.$mobile;
        $pwd      = md5($newCode);
        $userInfo = $this->userLoginModel->getUserInfoByAccount($account);
        if ($userInfo) return false;

        $data = array(
            'account'           => $account,
            'email'             => '@ffrj@' . $account,
            'nickname'          => '粉粉用户',
            'type'              => UK::getMobileCodeType('mobile_signin'),
            'passwd'            => $pwd,
            'registerChannel'   => 66
        );

        $userService = new UserService();
        $userService->initUser($data);
    }

    /**
     * 发送邮箱验证码
     */
    public function getEmailCode($info) {
        $uid    = AC::HOST_UID;
        $type   = $info['type'];
        $email = $info['email'];
        if (empty($email) || empty($type)) {
            AC::$errorNo    =   'UC007';//邮箱为空或格式错误
            return  FALSE;
        }

        // 验证传参
        $isEmail = UK::isEmail($email);
        $codeType   = UK::getMobileCodeType($type);
        if (!$isEmail || !$codeType) {
            AC::$errorNo  =   'GC034';//邮箱或类型格式错误
            return  FALSE;
        }

        // 修改密码需要查询账号是否存在
        $userBaseInfo   =   $this->autoUidModel->getUserBaseInfo(array('email' => $email));
        $emailExisted = empty($userBaseInfo) ? false : true;
        if (in_array($type, array("mobile_register", "mobile_bind")) && $emailExisted) {
            AC::$errorNo  =   'UC027';
            return  FALSE;
        }

        if ($type === "mobile_resetpasswd" && !$emailExisted) {
            AC::$errorNo  =   'UC039';
            return  FALSE;
        }

        // 验证码每小时只能发送 CODENUMPERHOUR 次，需要定时清理code表数据
        $codes = $this->autoUidModel->getEmailCodes(UK::getClientIp());
        if ($codes) {
            if ((AC::SERVER_TIME - AC::ONEMINUTE) < $codes[0]['time']) {
                AC::$errorNo  =   'GC055';
                AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            }

            if ((AC::SERVER_TIME - AC::ONEHOUR) < $codes[AC::CODENUMPERHOUR - 1]['time']) {
                AC::$errorNo  =   'GC066';
                AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            }
            if (AC::$errorNo) return  FALSE;
        }

        // 生成新的验证码
        $newCode = UK::generateCode(6);
        $result = $this->autoUidModel->addEmailCode($email, $codeType, $newCode, $uid);
        if (!$result) return false;

        //发送邮件
        $this->userLoginModel->sendEmailCode($email, $newCode);

        return true;
    }
    
    /**
     * 验证手机验证码是否正确
     * @param unknown $info
     * @return boolean
     */
    public function checkMobileCode ($info) {
        $uid    = AC::HOST_UID;
        $mobile = $info['mobile'];
        $code   = $info['code'];
        $type   = $info['type'];
        if (empty($mobile) || empty($type) || empty($code)) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }
        
        // 验证传参
        $isMobile   = UK::isMobile($mobile);
        $codeType   = UK::getMobileCodeType($type);
        if (!$isMobile || !$codeType) {
            AC::$errorNo  =   'UC020';
            return  FALSE;
        }
        
        $mobileCodeIsValid = $this->autoUidModel->checkMobileCodeIsValid($mobile, $code, $codeType);
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }
        
        return true;
    }

    /**
     * 验证邮箱验证码是否正确
     */
    public function checkEmailCode ($info) {
        $uid    = AC::HOST_UID;
        $email = $info['email'];
        $code   = $info['code'];
        $type   = $info['type'];
        if (empty($email) || empty($type) || empty($code)) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }

        // 验证传参
        $isEmail = UK::isEmail($email);
        $codeType   = UK::getMobileCodeType($type);
        if (!$isEmail || !$codeType) {
            AC::$errorNo  =   'GC034';
            return  FALSE;
        }

        $emailCodeIsValid = $this->autoUidModel->checkEmailCodeIsValid($email, $code, $codeType);
        if (AC::$errorNo) {
            UK::varDump(AC::$errorNo, __METHOD__);
            return  FALSE;
        }

        return true;
    }

    /**
     * 发送邮箱验证码
     */
    public function getUserAccountByEmail($info) {
        $uid    = AC::HOST_UID;
        $email = $info['email'];
        if (empty($email)) {
            AC::$errorNo    =   'UC007';//邮箱为空或格式错误
            return  FALSE;
        }

        // 验证传参
        $isEmail = UK::isEmail($email);
        if (!$isEmail) {
            AC::$errorNo  =   'UC007';//邮箱为空或格式错误
            return  FALSE;
        }

        $cacheModel = new RedisModel();
        $cot = $cacheModel->getGuestFindAccountWithEmailCount($email);
        if ($cot >= AC::CODENUMPERHOUR){
            AC::$errorNo = 'GC067';//超过今日发送次数上限
	        AC::$errorMsg  =   '验证码发送太频繁，请稍后再试';
            return false;
        }
        $cot ++;

        // 修改密码需要查询账号是否存在
        $userBaseInfo   =   $this->autoUidModel->getUserBaseInfo(array('email' => $email));
        if (empty($userBaseInfo)) {
            AC::$errorNo  =   'UC039';
            return  FALSE;
        }

        $username = '';
        $accountType = UK::getAccountTpye($userBaseInfo['account']);
        if ($accountType == AC::ACCOUNT_TYPE_MOBILE){
            $username = str_replace('mobile-86-', '', $userBaseInfo['account']);
        }elseif ($accountType == AC::ACCOUNT_TYPE_FENFEN_ACCOUNT){
            $username = $userBaseInfo['account'];
        }else{
            AC::$errorNo  =   'UC039';
            return  FALSE;
        }

        //发送邮件
        $this->userLoginModel->sendEmailUserAccount($email, $username);
        $cacheModel->setGuestFindAccountWithEmailCount($email, $cot);

        return true;
    }
    
    // 第三方绑定
    private function openUidBind($account, $extra, $type, $info){
    	 
    	if(empty($extra)){
            AC::$errorNo    =   'UB077';
            return FALSE;
    	}
    	 
    	$extra1 = UK::parse_query($extra);
    	$extra = array();
    	$extra['open_uid'] = UK::getstr($extra1['open_uid'], 80, "", 1) ;
    	$extra['open_token'] = UK::getstr($extra1['open_token'], 50, "", 1) ;
    	$extra['create'] =  intval($extra1['create']) < 1 ? AC::SERVER_TIME : intval($extra1['create']);
    	$extra['expire'] = intval($extra1['expire']);
    	$extra['nickname'] = UK::getstr($extra1['nickname'], 32, "", 1) ;
    	
    	if (empty($extra['open_uid']) || empty($extra['open_token'])){
    	    AC::$errorNo    =   'UB077';
    	    return FALSE;
    	}
		
    	if($type == AC::ACCOUNT_TYPE_QQ){
            $platform = 'qq';
    	}elseif($type == AC:: ACCOUNT_TYPE_WEIBO){
            $platform = 'weibo';
    	}elseif($type == AC:: ACCOUNT_TYPE_WECHAT){
            $platform = 'wechat';
    	}
    	
    	$openUser   =  UK::getThirdPartyUser($platform,  $extra['open_uid']);
    	$result = $this->userLoginModel->getUserInfoByAccount($openUser);
    	if(!empty($result)){
            if ($platform == 'qq'){
    	        AC::$errorNo  = 'UB023';
    	    }
    	    if ($platform == 'weibo'){
    	        AC::$errorNo  = 'UB024';
    	    }
    	    if ($platform == 'wechat'){
    	        AC::$errorNo  = 'UB025';
    	    }
            return FALSE;// 绑定的账号已存在
    	}
    	
    	// 初始化数据库
    	$param = array(
    	    'uid'           =>  $info['uid'],
    	    'account'       =>  $openUser,
    	    'type'          =>  $type,
    	    'nickname'      =>  $info['nickname'],
    	    'passwd'        =>  md5($openUser).'@ffrj',
    	    'open_type'     =>  $type,
    	    'connent_type'  =>  0,
    	    'open_token'    =>  $extra['open_token'],
    	    'extra'         =>  UK::JsonFormat($extra)
    	);
    	 
    	$result = $this->initUserLoginAndConnect($param);
    	if (empty($result)) {
    	    UK::varDump(AC::$errorNo, __METHOD__);
    	    return  false;
    	}
    	
    	return true;
    }
    
    private function initUserLoginAndConnect ($param) {
        $initConnect = $this->initUserConnect($param);
        if(empty($initConnect)){
            AC::$errorNo  = 'UL088';
            return false;
        }
        
        $initLogin = $this->initUserLogin($param);
        if (empty($initLogin)) {
            return  false;
        }
        
        return true;
    }
    
    private function initUserConnect ($param) {
        if (empty($param['uid']) || empty($param['account'])) {
            return false;
        }
        
        $connect = array(
            'open_type'        =>  $param['open_type'],
            'connent_type'     =>  $param['connent_type'],
            'uid'              =>  $param['uid'],
            'account'          =>  $param['account'],
            'open_token'       =>  $param['open_token'],
            'extra'            =>  $param['extra'],
            'status'           =>  0
        );
        
        $result = $this->userModel->addUserConnent($connect);
        return $result;
    }
    
    private function initUserLogin ($param) {
        if (empty($param['uid']) || empty($param['account']) || empty($param['passwd'])) {
            return false;
        }
        
        $login = array(
            'uid'      =>  $param['uid'],
            'account'  =>  $param['account'],
            'type'     =>  $param['type'],
            'nickname' =>  $param['nickname'],
            'passwd'   =>  $param['passwd'],
            'status'   =>  0
        );
        
        $result = $this->userLoginModel->initUserLogin($login);
        return $result;
    }
    
    // 解除原来的绑定
    private function accountUnbind($info){
    
    	$type   =  UK::getstr($info['type'], 20);
    	$uid 	=  AC::HOST_UID;
    	 
    	if(empty($type) || empty($uid) ){
            AC::$errorNo    =   'UC088';
            return FALSE;
    	}
    	 
    	// 用户名不能被解绑
    	$types = array("open_qq","open_weibo","open_wechat", "mobile");
    	if(!in_array($type, $types)){
            AC::$errorNo    =   'UB011';
            return FALSE;   // type类型错误
    	}
    
    	$bind_type = AC::ACCOUNT_TYPE_QQ;
    	if ($type == 'open_weibo'){
            $bind_type = AC::ACCOUNT_TYPE_WEIBO;
    	}elseif ($type == 'open_wechat'){
    	    $bind_type = AC::ACCOUNT_TYPE_WECHAT;
    	}elseif ($type == 'mobile'){
    	    $bind_type = AC::ACCOUNT_TYPE_MOBILE;
    	}
    	 
    	$connent = $this->userModel->getUserConnnetByAccount($uid, $bind_type);
    	
    	if( empty($connent) ) {
            AC::$errorNo    =   'UB044';
            return FALSE;   // 要解绑的账号不存在
    	}
    	 
    	// 不能解绑注册时的用户账号
    	if($connent['connent_type'] == 1 ){
            AC::$errorNo    =   'UB055';
            return FALSE;   // 注册账号不能被解绑
    	}
    	
    	$data = AC::$hostUserBaseInfo;
    	if($connent['open_id'] == $data['account']){
            AC::$errorNo    =   'UB055';
            return FALSE;   // 注册账号不能被解绑
    	}
    	 
    	$result = $this->userModel->delUserConnnet($uid, $bind_type);
    	if (empty($result)){
            AC::$errorNo    =   'UC0122';
            return FALSE;
    	}
    	
    	$result = $this->userLoginModel->delUserInfoByAccount($connent['open_id'],$uid);
    	if (empty($result)){
            AC::$errorNo    =   'UC0111';
            return FALSE;
    	}
    	
    	$this->addAccountBindOrUnbindLog($uid, 'accountunbind', $data['account'], array('account' => $connent['open_id'], 'type' => $type, 'extra' => ''));
    	return TRUE;
    }
    
    private function addUserConnent($info){

        $info['uid']    =    intval($info['uid']);
        if ($info['uid'] < 1){
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }
        if (empty($info['status'])){
            $info['status']    = 0;
        }
        $result = $this->userModel->addUserConnent($info);
        if ($result){
            return TRUE;
        }
        return FALSE;
    }
    
    /*
     * 获取用户帐号映射数据
     * @param unknown $info
     * @return boolean|StdClass|multitype:NULL
     */
    public function getConnent($param = array()){
    	$uid    =  AC::HOST_UID;
    	if ($param['uid']) $uid = intval($param['uid']);
        if (empty($uid)) {
            AC::$errorNo    =   'UC001';
            return  FALSE;
        }
        
        // 获取当前账号
        $defaultConnect = $this->getDefaultConnect($uid);
        
        // 获取绑定账号列表
        $result = $this->getUserConnnets($uid);
        array_push($result, $defaultConnect);
        
        // 组装数据
	    $data = $tmp = array();
        foreach($result as $value ){
            $tmp = $this->changeUserConnentData($value);
            if ($tmp) {
                $data['connents'][] = $tmp;
            }
        }
        $data['counts']    =    count($data['connents']);
        
        return $data;
    }

    private function getUserConnnets($uid){
        $result = $this->userModel->getUserConnnets($uid);
        if(!$result){
            return array();
        }
        foreach($result as &$value){
           $value['accountType']=2;
        }
        return $result;
    }

    /**
     * 添加用户注册帐号到绑定信息表
     * 
     * @param unknown $uid
     */
    private function getDefaultConnect($uid){
        $info = $this->autoUidModel->getUserInfo($uid, false, 0, false);
        $connent =array(
            'uid'           =>  $info['uid'],
            'open_type'     =>  UK::getAccountTpye($info['account']),
            'connent_type'  =>   1,
            'open_id'       =>  $info['account'],
            'open_token'    =>  '',
            'accountType'   => 1//账户类型是注册账户
        );

        return $connent;
    }
    
    /*
     * 组装并返回帐号映射数据
     * @param unknown $info
     * @return multitype:number Ambigous <string, unknown>
     */
    private function changeUserConnentData($info){
        $data = array(
                'uid'        =>    '0',
                'account'    =>    '',
                'type'       =>    '',
                'time'       =>    '0',
                'nickname'   =>    '',
                'expire'     =>    '0',
                'unbind'     =>    '0',
                'email'      =>    '',
                'accountType'    =>    '0',
        );
        
        $info['open_type'] = UK::getAccountBindTypeOrOpenType($info['open_type'], true);
        
        isset($info['uid'])            &&    $data['uid']        =    strval($info['uid']);
        isset($info['open_id'])        &&    $data['account']    =    strval($info['open_id']);
        isset($info['open_type'])      &&    $data['type']       =    strval($info['open_type']);
        isset($info['time'])           &&    $data['time']       =    strval($info['time']);
        isset($info['connent_type'])   &&    $data['unbind']     =    intval($info['connent_type']);
        isset($info['accountType'])    &&    $data['accountType']=    intval($info['accountType']);
        
        // 手机号
        if (UK::getAccountTpye($data['account']) == AC::ACCOUNT_TYPE_MOBILE) {
            $data['account'] = substr($data['account'], strlen('mobile-'));
        }
        
        // extras open_uid,open_token,create(创建时间),expire(token过期时间),nickname(昵称)
        if (!empty($info['extra'])){
            $extra = json_decode($info['extra'], true);
            $data['nickname'] = strval($extra['nickname']);
            $data['expire']   = strval($extra['expire']);
        }

        if (in_array($info['open_type'], array('fenfen','mobile'))){
            $autoInfo = $this->autoUidModel->getUserInfo($data['uid']);
            if ((strpos('a'.$autoInfo['email'], '@ffrj@') == 1) || empty($autoInfo) ){
                $autoInfo['email'] = '';
            }
            $data['email']    =    $autoInfo['email'];
            $data['unbind'] = 1;
        }
        if (empty($data['account'])) return array();
        
        return $data;
    }
    
    /**
     * 登陆、注册添加记录
     * @param unknown $uid
     * @param unknown $action
     * @param unknown $account
     * @param unknown $nickname
     */
    private function addLoginOrRegisterLog ($uid, $action, $account, $nickname) {
        $info = array('nickname' => $nickname);
        
        $this->userAccountLogModel->addUserAccountLog($uid, $action, $account, $info);
    }
    
    /**
     * 修改密码添加记录
     * @param unknown $uid
     * @param unknown $action
     * @param unknown $account
     */
    private function addModifyPasswdLog ($uid, $action, $account) {

        $this->userAccountLogModel->addUserAccountLog($uid, $action, $account, array());
    }
    
    /**
     * 账号绑定、解绑添加记录
     * @param unknown $uid
     * @param unknown $action
     * @param unknown $account
     * @param unknown $param
     */
    private function addAccountBindOrUnbindLog ($uid, $action, $account, $param) {
        $info = array('account' => $param['account'], 'type' => $param['type'], 'extra' => $param['extra']);
        
        $this->userAccountLogModel->addUserAccountLog($uid, $action, $account, $info);
    }
    
    /**
     * 获取账号类型信息(mobile、fenfen、qq、wechat、weibo等)
     * @param unknown $account
     * @return boolean|Ambigous <string, unknown>
     */
    private function getAccountPlatform ($account) {
        if (empty($account)) return false;
        
        $currentAccountType = UK::getAccountTpye($account);
        if (UK::isMobile($account)) $currentAccountType = AC::ACCOUNT_TYPE_MOBILE;
        $result = UK::getAccountBindTypeOrOpenType($currentAccountType, true);
        
        return $result;
    }
    
    /**
     * 获取兑吧登陆链接
     * @param unknown $param
     * @return multitype:string
     */
    public function getDuiBaAutoLoginUrl ($param) {
        $host_uid = AC::HOST_UID;
        $redirect = $this->filterQueryUrlOfDuiBa($param['redirect']);
        $coin     = 0;
        
        if ($host_uid > 0) {
            $api      = UK::getMallApi($host_uid);
            $userCoin = $api->getUserCoin();
            if ($userCoin && $userCoin['balance'] > 0) {
                $coin = $userCoin['balance'];
            }
        }else{
            $host_uid = 'not_login';
        }
        
        $new_level  = $this->translateDuiBaLevel($host_uid);
        $url = $this->buildCreditAutoLoginRequest($host_uid, $coin, $new_level, $redirect);
        return array('url' => $url);
    }

    public function vipOperate($param){
        $action = trim($param['action']);
        if (!in_array($action, [
            'followRule', 'source','shieldUser','unShield', 'setUserUnFollowMessage', 'getUserSettingInfo',
            'getUserShieldStatus'
        ])){
            AC::$errorNo    =   'SA004';
            return  ' Error : call do is not exists in UserController! ';
        };
        $param['uid'] = isset($param['uid']) ? intval($param['uid']) : 0;
        if ($param['uid']<1 || $param['uid']!=AC::HOST_UID){
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        $vipInfo = $this->autoUidModel->getUserVipInfo($param['uid']);
        if (empty($vipInfo) && $action != 'getUserSettingInfo'){
            AC::$errorNo    =   'VIP002';//还不是会员
            return  FALSE;
        }
        $action .= 'ByVip';
        return $this->{$action}($param);
    }

    private function followRuleByVip($param){
        $uid = $param['uid'];
        $rule = isset($param['rule']) ? intval($param['rule']) : -1;
        if ( $rule<0 || $rule>1){
            AC::$errorNo    =   'VIP001';
            return  FALSE;
        }
        $set = [ 'follow_rule'=>$rule ];
        $result = $this->autoUidModel->updateUserVipInfo($set, $uid);
        return $result ? true : false;
    }

    private function sourceByVip($param){
        $source = isset($param['source']) ? trim($param['source']) : '';
        $source = UK::cleanStr($source);
        $source = UK::getstr($source);
        $len = mb_strlen($source, 'UTF-8');
        if ($len>20){
            AC::$errorNo    =   'VIP003';//来源长度错误
            return  FALSE;
        }
        $set = [ 'diy_source'=>$source ];
        $result = $this->autoUidModel->updateUserVipInfo($set, $param['uid']);
        return $result ? true : false;
    }

    public function deviceInfo($param){
        $default_device = [
            'devices' => [
                [ 'id'=>1, 'vip'=>0, 'name'=>'Android', 'defaults'=>1 ]
            ]
        ];
        $manufacturer = isset($param['manufacturer']) ? trim($param['manufacturer']) : '';
        $model = isset($param['model']) ? trim($param['model']) : '';
        $device = isset($param['device']) ? trim($param['device']) : '';
        if (empty($manufacturer) || empty($model) || empty($device)){
            return $default_device;
        }
        $ret['devices'] = [];
        if (strtolower($manufacturer)!='apple'){
            $ret['devices'][] = $default_device['devices'][0];
        }else{
            $ret['devices'][] = [ 'id'=>2, 'vip'=>0, 'name'=>'iOS', 'defaults'=>1 ];
        }
        $infos = $this->userModel->getDeviceInfo($model, $device);
        if (empty($infos)){
            return $ret;
        }
        foreach ($infos as $info){
            $name = $info['pname']?$info['pname']:$info['market_name'];
            if (empty($name))continue;
            $ret['devices'][] = [ 'id'=>$info['id'], 'vip'=>0, 'name'=>$name ];
        }
        $ret['devices'][0]['defaults'] = 1;
        $ret = array_reverse($ret);
        return $ret;
    }

    public function submitDevice($param){
        $manufacturer = isset($param['manufacturer']) ? trim($param['manufacturer']) : '';
        $model = isset($param['model']) ? trim($param['model']) : '';
        $device = isset($param['device']) ? trim($param['device']) : '';
        $os = AC::$appInfoList[2];
        $diy = isset($param['diy']) ? trim($param['diy']) : '';
        if (empty($manufacturer) || empty($model) || empty($device) || empty($os)){
            AC::$errorNo = 'VIP001';
            return false;
        }
        $infos = $this->userModel->getDeviceAllInfo($model, $device);
        if ($infos)return true;
        $info = [
            'manufacturer' => $manufacturer,
            'os' => $os,
            'device' => $device,
            'model' => $model
        ];
        $diy && $info['diy'] = $diy;
        $res = $this->userModel->addDevice($info);
        return $res ? true : false;
    }
    
    private function filterQueryUrlOfDuiBa ($url, $f = array('appItemId', 'itemId', 'path', 'id')) {
        $url = str_replace("&none","",$url);
        $url = $this->unsetParam($url, 'spm');
        $url = $this->unsetParam($url, 'visits');
        return $url;

    	$url_arr = explode('?', $url);
    	$query_arr = explode('&', $url_arr[1]);
    
    	$query = '';
    	foreach ($query_arr as $val) {
    		if (in_array(substr($val, 0, strpos($val, '=')), $f)) {
    			$query .= $val.'&';
    		}
    	}
    	$query = trim($query, '&');

        $res = $url_arr[0];
        if ($query) {
            $res .= '?'.$query;
        }

    	return strval($res);
    }

    private function unsetParam($url, $param ) {
        return preg_replace(
            array("/{$param}=[^&]*/i", '/[&]+/', '/\?[&]+/', '/[?&]+$/',),
            array(''               , '&'     , '?'       , ''        ,),
            $url
        );
    }
    
    /**
     * 获取用户等级信息、达人情况，转换成兑吧等级
     * @param unknown $uid
     * @return number
     */
    private function translateDuiBaLevel ($host_uid) {
        $host_uid = intval($host_uid);
        $level = $medal_id = 0;
        if ($host_uid) {
            $userInfo = $this->getUserInfo(array('uid' => $host_uid));
            if ($userInfo) {
                $level    = $userInfo['userMember']['level'];
                $medal_id = $userInfo['userInfo']['ability_level'];
            }
        }
        
        // 0-39
        $new_level = floor(abs($level)/10);
        if ($new_level > 39 || $medal_id) $new_level = 39;
    
        return $new_level;
    }

    /**
     * 生成自动登录地址
     * 通过此方法生成的地址，可以让用户免登录，进入积分兑换商城
     * @param unknown $uid
     * @param unknown $credits
     * @return string
     */
    private function buildCreditAutoLoginRequest($uid, $credits, $vip, $redirect = ''){
        $url        = AC::getProtocolUriByOS(AC::$duibaAutoLoginUrl);
        $appKey     = AC::$duibaAppKey;
        $appSecret  = AC::$duibaAppSecret;
        $timestamp  = AC::SERVER_TIME * 1000 . "";
        $array      = array( "uid" => $uid, "credits" => $credits, "vip" => $vip, "appSecret" => $appSecret, "appKey" => $appKey, "timestamp" => $timestamp, "redirect" => $redirect);
        $sign       = UK::generateDuiBaSign($array);
        $url        = $url . "uid=" . $uid . "&credits=" . $credits ."&vip=".$vip. "&appKey=" . $appKey . "&sign=" . $sign . "&timestamp=" . $timestamp."&redirect=".$redirect;
        return $url;
    }

    /**
     * 获取用户角色
     * @param $param
     * @return array|bool|object
     */
    public function getUserRole($param)
    {
        if(empty($param['uid']) && empty($param['uuid']))
        {
            return false;
        }

        $service = new UserRoleService($param['uid'], $param['uuid']);
        return $service->getUserRole();
    }

    /**
     * 修改用户角色
     * @param $param
     * @return array|bool|object
     */
    public function setUserRole($param)
    {
        if(empty($param['uid']) && empty($param['uuid']))
        {
            return false;
        }

        $service = new UserRoleService($param['uid'], $param['uuid']);
        return $service->setUserRole($param);
    }

    #################  屏蔽用户  start  #####################

    /**
     * 屏蔽用户
     * @param $param
     * @return array|bool
     */
    private function shieldUserByVip($param)
    {
        $uid        = isset($param['uid']) ? intval($param['uid']) : 0;
        $shieldUid  = isset($param['shieldUid']) ? intval($param['shieldUid']) : 0;
        if($uid < 1 || $shieldUid < 1) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        if($uid == $shieldUid) {
            AC::$errorNo    =   'UC041';
            AC::$errorMsg   =   '不能屏蔽自己';
            return  FALSE;
        }

        $userInfo       = $this->autoUidModel->getUserInfo($uid);
        $shieldUserInfo = $this->autoUidModel->getUserInfo($shieldUid);
        if(empty($userInfo) || empty($shieldUserInfo)) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        //是否超过10个数量限制
        $max = AC::SERVER_TIME;
        $min = AC::SERVER_TIME - AC::ONEDAY;
        $userShieldCount = $this->diaryListCacheModel->getUserShieldCount($uid, $min, $max);
        if($userShieldCount >= 10) {
            AC::$errorNo    =   'UC040';//最多同时屏蔽10个用户
            AC::$errorMsg   =   '已达到屏蔽上限10个，暂时无法屏蔽';
            return  FALSE;
        }

        //屏蔽用户
        $this->diaryListCacheModel->setUserShieldList($uid, $shieldUid, AC::SERVER_TIME);
        //更新用户屏蔽列表
        $result = $this->updateUserShieldList($uid);

        if($result) {
            return ['shieldUser' => true];
        }else{
            return ['shieldUser' => false];
        }
    }

    /**
     * 解除屏蔽
     * @param $param
     * @return array|bool
     */
    private function unShieldByVip($param)
    {
        $uid        = isset($param['uid']) ? intval($param['uid']) : 0;
        $shieldUid  = isset($param['shieldUid']) ? intval($param['shieldUid']) : 0;
        if($uid < 1 || $shieldUid < 1) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        $userInfo       = $this->autoUidModel->getUserInfo($uid);
        $shieldUserInfo = $this->autoUidModel->getUserInfo($shieldUid);
        if(empty($userInfo) || empty($shieldUserInfo)) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        //解除屏蔽
        $this->diaryListCacheModel->removeUserShieldListItem($uid, $shieldUid);
        //更新用户屏蔽列表
        $result = $this->updateUserShieldList($uid);
        if($result) {
            return ['unShield' => true];
        }else{
            return ['unShield' => false];
        }
    }


    /**
     * 检查用户是否是否被屏蔽
     * @param $param
     * @return array|bool
     */
    private function getUserShieldStatusByVip($param) {
        $uid        = isset($param['uid']) ? intval($param['uid']) : 0;
        $shieldUid  = isset($param['shieldUid']) ? intval($param['shieldUid']) : 0;
        if($uid < 1 || $shieldUid < 1) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        $userInfo       = $this->autoUidModel->getUserInfo($uid);
        $shieldUserInfo = $this->autoUidModel->getUserInfo($shieldUid);
        if(empty($userInfo) || empty($shieldUserInfo)) {
            AC::$errorNo    =   'VIP001';//参数错误
            return  FALSE;
        }
        //检查用户是否被屏蔽
        $shieldStartTime =  $this->diaryListCacheModel->findUserShieldList($uid, $shieldUid);
        if(!empty($shieldStartTime) && $shieldStartTime > AC::SERVER_TIME - AC::ONEDAY) {
            return ['shieldStatus' => true];
        }else{
            return ['shieldStatus' => false];
        }
    }

    /**
     * 更新用户屏蔽列表
     * @param $uid
     * @return bool|int|resource
     */
    private function updateUserShieldList($uid){
        $lasTime = AC::SERVER_TIME - AC::ONEDAY;
        //清除过期屏蔽用户列表
        $this->diaryListCacheModel->removeUserShieldListItemByScore($uid, AC::ONEDAY, $lasTime);
        //更改数据库
        $userShieldList = $this->diaryListCacheModel->getUserShieldList($uid, true);
        $setInfo = [
            'extra' =>  json_encode($userShieldList)
        ];
        $result = $this->userSettingModel->saveSetting($uid, $setInfo);
        return $result;
    }

    #################  屏蔽用户  end   #####################

    /**
     * 会员设置是否接受取关通知
     * @param $param
     * @return bool|int|resource
     */
    private function setUserUnFollowMessageByVip($param)
    {
        if(empty($param['uid'])) {
            return false;
        }

        $setInfo = $param['unFollowPush'] == 1 ? '1' : '0';
        $userSettingModel = new UserSettingModel();
        $set = ['string3'=> $setInfo];
        $result = $userSettingModel->saveSetting($param['uid'], $set);
        if(!$result){
            return false;
        }
        $settingInfo = $this->getUserSettingInfoByVip(['uid' => $param['uid']]);
        return $settingInfo;
    }

    /**
     * 获取用户设置信息
     * @param $param
     * @return array|bool|mixed
     */
    private function getUserSettingInfoByVip($param)
    {
        if(empty($param['uid'])) {
            return false;
        }
        $unFollowPush = false;
        $userSettingModel = new UserSettingModel();
        $userSettingInfo = $userSettingModel->getSettingInfo($param['uid']);
        if($userSettingInfo && $userSettingInfo['string3'] == '1'){
            $unFollowPush = true;
        }
        $result = [
            'uid' => $param['uid'],
            'settingInfo' => [
                'unFollowPush' => $unFollowPush
            ],
            'created_at' => isset($userSettingInfo['created_at']) ? $userSettingInfo['created_at'] : AC::SERVER_TIME,
            'updated_at' => isset($userSettingInfo['updated_at']) ? $userSettingInfo['updated_at'] : AC::SERVER_TIME,
        ];
        return $result;
    }
}

